有 2 个模型Product
,Variant
其中一个Product
hasManyVariant
和一个Variant
belongsTo Product
。这两个模型还包含许多其他关系。
问题:您如何使用 Eloquent 选择所有变体->where('color','red')
及其相关Product
必须满足->where('price', '>' '50')
?必须保留返回结果集中 Variant 的所有关系。
当join
在 Eloquent 模型上使用 a 时,所有关系都将丢失,除了products
已连接的。例如:$variant->product->id
有效但无效$variant->someOtherModel->id
。
$variants =Variants::where('color', 'red')
->join('products', 'variants.product_id', '=', 'products.id')
->where('product.price', '>', 10)
->paginate(10);
foreach($variants as $variant) {
echo $variant->product->id; //works
echo $variant->someOtherModel->id; // error, undefined function
}
你们是如何维持所有人$variant
的关系的?
每个WHERE
子句似乎都使用OR
而不是链接AND
!这太疯狂了!
$variants = Variant::where('color', 'red')
->with(array('Product' => function($query) {
if(Input::get('price') $query->where('price', '>', 10);
if(Input::get('brand') $query->where('brand', Input::get('brand'));
}))
->paginate(10);