laravellaravel-5eloquent

How to access table, related to pivot table in whereHas?


I have two models One and Two, related via pivot table 'one_two', which has own model OneTwo with hasOne Three. Now I want to get all One instances filtered by value in Three. This is what I tried and didn't success:

$ones = One::with('twos')->whereHas('twos', function ($q) {
    $q->where('threes.value', 'yes');
})->get();

How to do such thing?

Table ones : id,field1

Table twos : id,field2

Table one_two : id,one_id, two_id, pivot_field,

Table threes : id, one_two_id, value

One <=> Two: many to many

Three => OneTwo: one to one


Solution

  • For this sort of thing, I don't think you can directly use relationships on a Pivot model due to the way laravel structures its many to many queries.

    One way to get around this would be to define a hasMany relationship between One and OneTwo so that you can apply the constraints easily but it won't mean you have to give up your existing relationships (you're purely using this relationship to scope your query) i.e.

    One Model

    public function oneTwo() 
    {
        return $this->hasMany(OneTwo::class);
    }
    

    This way you can then structure you query like this:

    $ones = One::with('twos')->whereHas('oneTwos.three', function ($q) {
        $q->where('value', 'yes');
    })->get();
    

    In the above example I'm assuming you relationship is called three as it is a hasOne relationship. If it is threes you just need to change the whereHas relationship to 'oneTwos.threes'.