2
From what I understand in the documentation, to the whereHas it is necessary to have a get at the end of query, but I need to use the first, since I’m picking up the information from a particular record. The way the code is, it presents no error, but it ignores the Where within the Function and ends up returning all results.
$serie = $this->serie->where('slug', $slug)
->whereHas('lista', function ($q){
$q->where('user_id', Auth::user()->id);
})
->first();
If I make one more query, works normal but would like to do everything in one to get cleaner the code.
$lista = Lista::where('serie_id', $serie->id)
->where('user_id', Auth::user()->id)
->first();
MODEL SERIE
namespace App;
use Illuminate\Database\Eloquent\Model;
class Serie extends Model{
protected $primaryKey = 'id';
protected $table = 'series';
protected $fillable = ['titulo', 'titulo_original', 'sinopse',
'poster', 'data_lancamento', 'trailer', 'emissora_id',
'status', 'capa', 'slug'];
protected $dates = ['created_at', 'updated_at'];
public $timestamps = true;
public function lista(){
return $this->hasMany('App\Lista');
}
}
MODEL LIST
namespace App;
use Illuminate\Database\Eloquent\Model;
class Lista extends Model
{
protected $primaryKey = 'id';
protected $table = 'listas';
protected $fillable = ['descricao', 'serie_id', 'user_id'];
protected $dates = ['created_at', 'updated_at'];
public $timestamps = true;
public function serie(){
return $this->belongsTo('App\Serie');
}
}
SAIDA TOSQL
select * from `series` where `slug` = ? and
exists (select * from `listas`
where `series`.`id` = `listas`.`serie_id` and `user_id` = ?)
A user can add each series to a list. It can only have each series in a list only. And a series can be in the list of all users.