Eloquent: Calling Where in Relation

I have the following Eloquent ORM request.

$products2 = Product::with('metal', 'metal.fixes', 'metal.fixes.currency') ->where('metal_id', '=', 1) ->get()->toArray(); 

The result of this query is as follows:

http://pastebin.com/JnDi7swv

I want to narrow my query only to display products, where fixes.currency_id = 1 .

 $products2 = Product::with('metal', 'metal.fixes', 'metal.fixes.currency') ->where('metal_id', '=', 1) ->where('metal.fixes.currency_id', '=', 1) ->get()->toArray(); 

Can someone help me with this second one, please, because I am getting the following error:

 SQLSTATE[42S22]: Column not found: 1054 Unknown column 'metal.fixes.currency_id' in 'where clause' (SQL: select * from `products` where `metal_id` = ? and `metal`.`fixes`.`currency_id` = ?) (Bindings: array ( 0 => 1, 1 => 1, )) 

Solved with the help of Rob Gordin:

 $products2 = Product::with(array( 'metal', 'metal.fixes.currency', 'metal.fixes' => function($query){ $query->where('currency_id', '=', 1); })) ->where('common', '=', 1) ->where('metal_id', '=', 1) ->get()->toArray(); 
0
source share
1 answer

You are looking for "Aager Load Constraints": http://laravel.com/docs/eloquent#querying-relations

 <?php $products2 = Product::with(array('metal', 'metal.fixes', 'metal.fixes.currency' => function($query){ $query->where('currency_id', '=', 1); })) ->where('metal_id', '=', 1) ->get()->toArray(); 
+2
source

Source: https://habr.com/ru/post/954123/


All Articles