【问题标题】:how to get rows related to same table through many to many relationship - Laravel如何通过多对多关系获取与同一张表相关的行 - Laravel
【发布时间】:2019-07-08 13:28:01
【问题描述】:

我有一个名为 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;

有没有更好的方法来做到这一点?

【问题讨论】:

  • 你想检索通过 $categories = Product::find($id)->categories; 获得的所有附加类别的产品?

标签: laravel many-to-many relationship


【解决方案1】:

我是使用常规 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();

【讨论】:

    【解决方案2】:
    // Basic usage
    $product = Product::findOrFail($id);
    
    $relatedProducts = Product::where('category', $product->category)->get();
    
    // If you want to skip the main product from appearing again in the related products collection do
    
    $relatedProducts = Product::where('category', $product->category)->where('id', '!=', $product->id)->get();
    
    
    // to simplify this, you can create a method in `Product` model class : 
    
    
    public function getRelatedProducts()
    {
    
        return self::where('category', $product->category)->where('id', '!=', $this->id)->get();
    }
    
    // and then do : 
    
    $product = Product::findOrFail($id);
    
    $relatedProducts = Product::getRelatedProducts();
    

    【讨论】:

      【解决方案3】:

      我发现在大多数情况下多对多关系令人不安,在这种情况下,最好创建另一个以一对多方式映射关系的表。在这种情况下,我认为在 products 表中有一个类别 id 列更容易,然后当您想要获取相关产品时,您只需使用查找类别与您想要的类别相同的产品,例如: $Products::where("product_id",$productId)->get();

      【讨论】:

        猜你喜欢
        • 2019-10-15
        • 1970-01-01
        • 2019-01-04
        • 2019-09-04
        • 1970-01-01
        • 2013-02-17
        • 1970-01-01
        • 2018-01-11
        • 2012-08-27
        相关资源
        最近更新 更多