我有一個ShopController。
我有一個ShopController。現在我正從資料庫中以隨機順序顯示產品。 以下是代碼
$productsLike = Product:: with('categories')->where('slug', '! =', $slug)->inRandomOrder()-> take(4)-> get();
我應該做什么來顯示與當前產品相同類別的產品?
uj5u.com熱心網友回復:
你可以用類別id檢查。
$productsLike = Product::with('categories'/span>)
->where('category_id_column', $category_id)
->where('slug', '!=', $slug)
->inRandomOrder()->take(4)->get()。
uj5u.com熱心網友回復:
我會在你的Product模型上做一個local scope以使事情可重復使用。
public function scopeRelatedProducts($query, $count = 10, $inRandomOrder = true)
{
$query = $query->where('category_id', $this-> category_id)
->where('slug' '!=' $this->slug)。
if ($inRandomOrder) {
$query->inRandomOrder()。
}
return $query-> take($count);
}
然后你可以做一些事情:
$related = Product:: relatedProducts(4, true)->with('categories')->get();
這假設你的Product表存盤與Category的關系的列遵循Laravel的命名慣例(例如:RelatedModelName_id)。
你也可以把slug_id替換成Product id
然后你可以在你的視圖中使用產生的$related變數,所以假設你在Product show控制器方法中使用上述內容,你可以做:
class ProductController
{
public function show (Product $product)
{
$related = $product-> relatedProducts(4, true)->with('categories')->get()。
return view('products.show', compact('product', 'related');
}
}
@foreach ($related as $item)
<h5>{{ $item->name }}</h5>
<p>{{ $item-> description }}</p>
@endforeach
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/332454.html
標籤:

