首页 > 解决方案 > 如何通过多对多关系获取与同一张表相关的行 - Laravel

问题描述

我有一个名为 Products 的模型,我需要将相关产品返回到视图中。所以我创建了另一个模型,叫做 Category,关系是多对多的。

我设法获得了相关产品,但每个产品都附有一个不太好的类别,这是我的代码:

$categories = Product::find($id)->categories;
$products = new Product;
$products = $products->toArray();
foreach ($categories as $cat) {
    array_push($products, Category::find($cat->id)->products);
}
return $products;

有更好的方法吗?

标签: laravelmany-to-manyrelationship

解决方案


我使用常规 SQL 查询完成了它,这是希望帮助某人的代码

$catIDs = DB::table('product_category')
            ->select('category_id')
            ->where('product_id', $id)
            ->pluck('category_id');

$productsIDs = DB::table('products')
                ->select('product_category.product_id')
                ->distinct()
                ->rightJoin('product_category', 'products.id', '=', 'product_category.product_id')
                ->whereIn('category_id', $catIDs)
                ->pluck('product_id');

$relatedProducts = Product::with('firstImage')
                        ->whereIn('id', $productsIDs)
                        ->where('id', '!=', $id)
                        ->inRandomOrder()
                        ->get();

推荐阅读