首页 文章

Eloquent和Joins不保留模型关系

提问于
浏览
0

有2个模型 ProductVariant ,其中 Product hasMany VariantVariant belongsTo Product . 两种模型还包含许多其他关系 .

Question: 如何使用Eloquent选择所有变体 ->where('color','red') ,其相关的 Product 必须满足 ->where('price', '>' '50') ?必须保留返回结果集中Variant的所有关系 .

当在Eloquent模型上使用 join 时,除了已加入的 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);

1 回答

  • 0

    急切的负载限制可以解决它:

    $Variants =Variants::where('color', 'red')
    ->with(array(
         'Product' => function($query) {
            $query->where('price', '>', 10);
         }
        ,'OtherModel'
        ,'FooBar'
    ))
    ->paginate(10);
    

相关问题