2016-08-16 36 views
0

我有一个产品表,我需要获得相关产品。这是我应该得到的相关产品:根据一些条件将结果添加到Eloquent中

获取具有相同MODEL_ID 12个产品

如果我得到了不到12个款产品则保持我得到了什么,并添加产品与同CATEGORY_ID,直到我完成了12种产品。

我在想这样的事情,但它不工作。

$products = Product::first(); 
$relatedProducts = Product::query(); 
$relatedProducts = $relatedProducts->where('model_id', $product->model_id)->take(12); 
$tmp_total = $relatedProducts->count(); 
if($tmp_total < 12) { 
    $relatedProducts->where('category_id', $product->category_id)->take(12); 
} 
return $relatedProducts->get(); 

回答

1

任何您添加的where子句都添加到原始查询中。

你需要一个新的查询第二个:

$product = Product::first(); 

$related = Product::where('model_id', $product->model_id)->take(12)->get(); 

if ($related->count() < 12) { 
    $related = $related->merge(
     Product::where('category_id', $product->category_id) 
       ->where('model_id', '!=', $product->model_id) 
       ->take(12 - $related->count()) 
       ->get() 
    ); 
} 

return $related; 
+0

只需要添加另外哪里排除2号查询当前MODEL_ID这样你就不会得到第一副本。 –

0
$product = Product::first(); 
$products = Product::where('model_id', $product->model_id) 
      ->take(12) 
      ->get(); 
$remain = 12 - $products->count(); 
if ($remain > 0){ 
    $additions = Product::where('category_id', $product->category_id) 
       ->take($remain) 
       ->get(); 
    $products->merge($additions); 
} 
return $products;