2016-08-16 135 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;