jeudi 21 février 2019

eager loading nested relations with condition

A user has many foo's. Each foo belongs to a bar.

I want to load all users and eager load them with all their foo's and bar's. However, I only want to load active foo's.

This gives me all foo's and bar's:

User::with('foos.bar');

How can I put a constrain that will only eager load active foo's?


This is what I tried

1)

User::with(['foos.bar' => function($q){
   $q->where('active','=',true);
}]);

This doesn't work. It throws the error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'active' in 'where clause' select * from bars where bars.id in (1, 2, 3, 4, 5, 6) and active = 1

2)

User::with(['foos.bar' => function($q){
       $q->join('foos','foos.bar_id','=','bar.id')
         ->where('foos.active','=',true);
    }]);

This gives me the expected result set of all users with an active foo. However, the relation bar is null for each foo.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire