Laravel 5.5: WhereHas in relationship many to one

2

From what I understand in the documentation, where whereHas works, you need to have a get at the end of the query , however I need to use first , since I'm getting information from a particular record. The way the code is, it does not display any errors, but it ignores the where within 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();

$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');
    }
}

TOSQL OUT

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 serie may be on the list of all users.

  

    
asked by anonymous 20.12.2017 / 13:15

1 answer

1

I believe that the most internal list, that is, the relationship list, has not been filtered, it is always good to load with #

$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

    
20.12.2017 / 15:13