Laravel 5.5 : Wherehas in relationship Many to one

Asked

Viewed 232 times

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.

inserir a descrição da imagem aqui

1 answer

1


I believe it was lacking to filter the more internal list, that is, the relationship, it is always good to make the charge with with, example:

$serie = $this->serie
        ->with(['lista' => function($q){
            $q->where('user_id', Auth::user()->id);
        }) 
        ->where('slug', $slug)
        ->whereHas('lista', function ($q){
            $q->where('user_id', Auth::user()->id);
        })
        ->first();

Reference: Constraining Eager Loads

Browser other questions tagged

You are not signed in. Login or sign up in order to post.