【问题标题】:Laravel : Using WITH and left join filter table dataLaravel:使用 WITH 和左连接过滤表数据
【发布时间】:2018-05-04 18:13:00
【问题描述】:

在我的查询中加入 4 个表。我得到了所有响应,但三个表具有相同的字段名称“标题”并且不匹配。那么我该如何解决这个问题。有什么方法可以在leftjoin 之前或leftjoin 查询之后过滤我想要的文件。

我的查询看起来像:

  $userPost =  Post::with(['product','postattributes' => function ($query) {
                        $query  ->leftjoin('attributes', 'attributes.id', '=', 'post_attributes.attribute_id')
                                ->leftjoin('categories', 'categories.id' , '=', 'attributes.category_id');
                    }])->whereUserId($user->id)->whereStatus("Active")
                    ->get();

然后响应 i gt:

 "postattributes": [
            {
                "id": 1,
                "attribute_id": 1,
                "post_id": 136,
                "created_at": "2018-04-27 18:46:28",
                "updated_at": "2018-04-27 18:46:28",
                "product_id": 1,
                "category_id": 1,
                "parent_id": null,
                "title": "Shape",
                "status": "Active",
                "sort_order": 1
            },
            {
                "id": 1,
                "attribute_id": 2,
                "post_id": 136,
                "created_at": "2018-04-27 18:46:28",
                "updated_at": "2018-04-27 18:46:28",
                "product_id": 1,
                "category_id": 1,
                "parent_id": null,
                "title": "Shape",
                "status": "Active",
                "sort_order": 1
            } 
        ]

现在我想在categories 表上使用title as category_title。 我该怎么做?

【问题讨论】:

    标签: laravel laravel-5.5


    【解决方案1】:

    您可以为此使用select

     $userPost =  Post::with(['product','postattributes' => function ($query) {
                        $query->select('categories.id', 'attribute_id','post_id', 'created_at', 'updated_at','product_id','category_id', 'parent_id', 'categoris.title as category_title', 'status', 'sort_order')
                              ->leftjoin('attributes', 'attributes.id', '=', 'post_attributes.attribute_id')
                              ->leftjoin('categories', 'categories.id' , '=', 'attributes.category_id');
                    }])->whereUserId($user->id)->whereStatus("Active")
                    ->get();
    

    select 中,您可以设置您需要的所有字段,在此示例中,我从您的列表中添加了所有字段。

    【讨论】:

      猜你喜欢
      • 2022-08-24
      • 2021-06-18
      • 2015-07-12
      • 1970-01-01
      • 1970-01-01
      • 2013-02-11
      • 1970-01-01
      • 2013-01-19
      • 1970-01-01
      相关资源
      最近更新 更多