【问题标题】:Laravel 5.1 - showing related products through pivot tableLaravel 5.1 - 通过数据透视表显示相关产品
【发布时间】:2016-02-08 16:37:43
【问题描述】:

我被困在这条路上太久了,无法自己解决,所以这是我的问题:

我的数据库被衣服填满了。我想根据颜色展示相关的衣服。

我的人际关系:

(Product.php)

public function colors(){
        return $this->belongsToMany('App\Color', 'colors_products', 'FK_product', 'FK_color');
    }

(颜色.php)

 public function products(){
        return $this->belongsToMany('App\Product', 'colors_products', 'FK_color', 'FK_product');
    }

所以每个product 都有多个colors。我想在同一页面上显示相关的作品。因此,如果我正在看一件颜色为“红色”和“黑色”的作品,我想展示标有“红色”和/或“黑色”的相关衣服。所以它不必既是红色又是黑色。

我怎样才能得到像我正在看的那件衣服一样具有一种(有时是多种)颜色的所有衣服?

更新

Product::with('colors')->whereIn('id', $arColors)->get(); 是解决方案的一部分。当我有 2 种颜色(红色和黑色)的产品时,我会看到只有黑色或只有红色的相关产品。但是当我看一个只有黑色的产品时,多个颜色的相关项目不显示。

【问题讨论】:

  • $arColor 数组中列出了哪些颜色?您如何识别数据库中的“红黑”?

标签: php laravel laravel-5 eloquent relationship


【解决方案1】:

NULL 的答案很接近。我认为您想为此使用 whereHas() 。鉴于您的颜色数组可以从您的活动产品中轻松获得,假设它被称为 $color_ids。

要加载与其中一种颜色匹配的所有其他产品,请尝试以下操作:

$related_products = Product::whereHas('colors', function($query) use ($color_ids) {
    $query->whereIn('id', $color_ids);
})->get();

whereIn() 记录在这里:http://laravel.com/docs/5.1/queries#where-clauses

whereHas() 记录在这里:http://laravel.com/docs/5.1/eloquent-relationships#querying-relations

【讨论】:

    【解决方案2】:

    如果您想使用关系并且可以使用视图(或使用支持它的数据库),您可以创建这样的视图:

    create 
        view related_products 
    as 
        select distint 
            a.FK_product as FK_product,
            b.FK_product as FK_related_product 
        from 
            colors_products as a 
        join colors_products as b 
            on (a.FK_color = b.FK_color and a.FK_product <> b.FK_product);
    

    这应该加入所有具有至少一种共同颜色的产品。

    现在您可以向模型添加关系,如下所示:

        public function relatedProducts()
        {
          return $this->belongstoMany('App\Product', 'related_products', 'FK_related_product');
        }
    

    【讨论】:

    • 非常感谢您的宝贵时间。不过,这不是我想要解决的方式。
    【解决方案3】:

    试试这个,希望对你有帮助。

    Color::with('products')->whereIn('color', ['red', 'black'])->get();
    

    这将为您提供颜色以及与之相关的所有产品。

    更新: 根据你的更新,你可以试试这个。

    Product::with(['color' => function($q) use ($colorArray) { 
                                 $q->whereIn('color', $colorArray); }])
           ->has('color')
           ->get();
    

    我没有运行这个,但希望能工作。

    【讨论】:

    • Product::with('colors')-&gt;whereIn('id', $arColors)-&gt;get(); 是解决方案的一部分。当我有 2 种颜色(红色和黑色)的产品时,我看到相关产品只有黑色或只有红色。但是当我看一个只有黑色的产品时,多个颜色的相关项目不显示。
    • 产品将包含在颜色对象中。
    • 感谢您的更新。我不想丢弃多种颜色的产品。 :) 仍然是一个问题:我收到了所有相关的产品,但也收到了错误的产品,甚至没有与该产品的链接.. :/
    • 它没有改变输出。仍然是没有任何链接的衣服。
    猜你喜欢
    • 2021-04-29
    • 2016-08-04
    • 1970-01-01
    • 2016-02-12
    • 2017-06-21
    • 2021-06-06
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    相关资源
    最近更新 更多