Laravel Enloquent - >与()和 - > select()相互冲突 [英] Laravel Eloquent ->with() and ->select() conflict with each other

查看:257
本文介绍了Laravel Enloquent - >与()和 - > select()相互冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个代码:

 文章
:: select('article_id','article_text')// ($ {$ b $ user'=> function($ q){
$ q-> select('user_id','user_name '); //这个工程很好
}
])
- > get();

在Eloquent中构建查询时,我们可以使用 - > with()来检索关联的模型。我们还可以附加 - > select()来确定从相关模型中选择哪些列。但是,看起来我们可以指定从我们查询的基本模型中选择哪些列。



在这个例子中,由于第一个 :: select ,返回的最终结果不包括 user ,因为它不包含在 :: select 列表。如果我把它包含在那里,那么它会引发关于列未找到的错误。雄辩不够明白,我的意思是关系,而不是列。



是否可以指定哪些列应从 user 以及文章

解决方案

你可以使用热切的加载约束选择所需的列,但是您仍然需要至少选择用于关系的列。



随机示例:

  User :: with(['ticket'=> function($ q){
$ q-> select(' user_id');
}]) - > select('id') - > get();

这些是返回关系结果所需的最小字段,并将它们附加到正确的



您需要从门票 user_id c $ c>和 id 用户。那些是用于这种关系的列。 ticket.user_id - > users.id



查询日志:

 '从`users`选择`id` 

'select`user_id` ```````````````````````''$'$ $ $ $ $ $ $ $ $ $ $ $ $字段为您提供所需的关系以返回结果,现在您可以为这些选择添加其他字段。



我希望有帮助。


Consider this code:

Articles
::select('article_id', 'article_text')  //This one does not work as expected
->with([
    'user' => function($q){
        $q->select('user_id', 'user_name'); // This one works fine
    }
])
->get();

When building query in Eloquent, we can use ->with() to retreive associated models. We can also attach ->select(), to determine which columns should be selected from associated model. However, looks like we loose possibility to specify which columns should be selected from the base model we are querying.

In this example, because of the first ::select, the final results returned do not include user, because it's not included in the ::select list. If I include it there, then it throws an error about column not found. Eloquent is not smart enough to understand that I mean relationship, not column.

Is it possible to specify which columns should be returned from user as well as from article ?

解决方案

You can select the columns you want with eager loading constraints but you still need to at the least select the columns that are used for the relationship.

Random example:

User::with(['tickets' => function ($q) {
    $q->select('user_id');
}])->select('id')->get();

Those are the minimum fields needed for that to return results for the relationship and have them attached to the correct models.

You would need to select a minimum of user_id from tickets and id from users. Those are the columns used for this relationship. tickets.user_id -> users.id

Query Log:

'select `id` from `users`'

'select `user_id` from `tickets` where `tickets`.`user_id` in ( .... )'

Having those fields gives you what you need for the relationship to return results, now you can add additional fields to those selects.

I hope that helps.

这篇关于Laravel Enloquent - >与()和 - > select()相互冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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