首页 > 解决方案 > laravel中如何根据多列进行关联

问题描述

我面临着基于多列创建关联的问题。这是我的代码和数组:-

$getdetails =  OrdersProduct::with('getattributes')->get();

还有我的OrdersProduct.php模型文件

public function getattributes(){
   return $this->hasMany('App\ProductsColor','product_id','product_id');
 }

请参阅下面的数组:-

  Array
  (
   [0] => Array
    (
        [order_id] => 100015390
        [product_id] => 1203
        [product_size] => 12
        [attributes] => Array
            (
                [0] => Array
                    (
                        [id] => 5748
                        [product_id] => 1203
                        [sku_website] => N7W84308-BLACK-10
                        [sku] => 8907613878595
                        [color] => 
                        [size] => 10
                        [price] => 2799
                        [stock] => 0
                        [ip_address] => 
                        [created_at] => 2018-08-07 16:15:36
                        [updated_at] => 2018-08-07 16:15:36
                    )

                [1] => Array
                    (
                        [id] => 5749
                        [product_id] => 1203
                        [sku_website] => N7W84308-BLACK-12
                        [sku] => 8907613878601
                        [color] => 
                        [size] => 12
                        [price] => 2799
                        [stock] => 0
                        [ip_address] => 
                        [created_at] => 2018-08-07 16:15:37
                        [updated_at] => 2018-08-07 16:15:37
                    )

            )

    )
)

我的预期输出如下: -

Array
(
[0] => Array
    (
        [order_id] => 100015390
        [product_id] => 1203
        [product_size] => 12
        [attributes] => Array
            (

                [0] => Array
                    (
                        [id] => 5749
                        [product_id] => 1203
                        [sku_website] => N7W84308-BLACK-12
                        [sku] => 8907613878601
                        [color] => 
                        [size] => 12
                        [price] => 2799
                        [stock] => 0
                        [ip_address] => 
                        [created_at] => 2018-08-07 16:15:37
                        [updated_at] => 2018-08-07 16:15:37
                    )

            )

    )
)

我想与 order_products 表中的 product_id 和 product_size 进行比较,形成 products_color 表,其中包含 product_id 和 size。谢谢

标签: phplaravellaravel-5eloquentquery-builder

解决方案


终于完成了。我已经在 getattributes 中添加了加入。希望它会在未来对其他人有所帮助:-

$getdetails =  OrdersProduct::with(['getattributes'=>function($query){
        $query->join('orders_products','orders_products.product_size','=','products_colors.size');
    }])->get();

推荐阅读