集合关系选择列不工作 Laravel [英] Collection Relationship Select columns not working Laravel

查看:54
本文介绍了集合关系选择列不工作 Laravel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试选择关系数据库 (product_detail) 的列 (id, title),但它根本不起作用.

I am trying to select columns (id, title) of the relationship database (product_detail) but it's not working at all.

我的查询:

RoomProduct::select('product_id', DB::raw('SUM(value) as total'))
          ->whereHas('room.offer', function($sql) use ($offer_id) {
              $sql->where('id', $offer_id);
          })->whereHas('product_detail', function($sql) use ($category_id) {
              $sql->select("id", "title")->with(['category' => function ($query) {
                $query->where('parent_id', $category_id);
            }])->orWhere('id', $category_id);
          })->groupBy("product_id")->get();

推荐答案

首先阅读这篇文章的评分最高的答案 -> Laravel - Eloquent Has"、With"、WhereHas"- 它们是什么意思?

First have a read of the top rated answer of this post -> Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

whereHas() 方法与 has() 方法相同,只是它允许您在闭包内提供额外的 where 子句.但是这两种方法都只返回具有您要求的关系的模型.但这并不意味着它会返回这些关系中的任何列.

The whereHas() method is the same as the has() method except it allows you to provide additional where clauses inside of your closure. But both of these methods only return models that have the relationship you have asked for. This does not mean it will return any columns in those relationships though.

您需要使用 with() 方法来获取您要查找的列,然后在您的选择中将它们引用为类似 select('product_id', DB::raw('SUM(value) as total'), 'product_detail.id', 'product_details.title')

You will need to use the with() method to obtain the columns you are looking for and then reference them in your select as something like select('product_id', DB::raw('SUM(value) as total'), 'product_detail.id', 'product_details.title')

希望对你有帮助!如果不清楚或有任何问题,我一定会尽快回复.

I hope this has helped you! If it's not clear or have any questions i'll be sure to respond as quick as possible.

这篇关于集合关系选择列不工作 Laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆