英文:
Laravel "with" does not work currently next to "get" method
问题
Laravel中with
在get
方法旁边带有参数时目前不起作用。
我编写了这段代码:
Page::with('user:id,name')->get();
目前这段代码可以正常工作,但我想要从pages
表中获取特定列(例如title
和body
),所以我编写了这段代码:
Page::with('user:id,name')->get(['title', 'body']);
但user
将为null
英文:
Laravel with
does not work currently next to get
method when get
has argument
I have two table that has one-to-many relationship.
I wrote this code:
Page::with('user:id,name')->get();
that work currently, but I want specific columns from pages
table (such as title
and body
) so I wrote this code:
Page::with('user:id,name')->get(['title', 'body']);
But user
will be null
答案1
得分: 0
使用select()
,并且需要添加外键也。
Page::with('user:id,name', function ($query) {
$query->select('title', 'body', 'UserId');
})->get(); // 如果外键是`UserId`,你应该在这里使用你的列名
英文:
Use select()
and you need to add foreign key also
Page::with('user:id,name'=> function($query) { $query->select('title','body','UserId'); }])->get(); // If foreign key is `UserId` you should use your column name here
答案2
得分: 0
你必须从 pages
中选择 user_id
字段。这是用于获取与查询返回的所有页面相关联的用户的字段。这是分开的查询。如果没有 user_id
字段可用,Eloquent 如何查询以获取所有帖子所属的用户呢?
Page::with('user:id,name')->get(['title', 'body', 'user_id']);
这意味着返回的所有页面结果/对象都会有一个 user_id
列,然后可以从集合中取出该列,然后进行查询以加载所有用户,然后将它们与它们的父对象匹配。
get
方法定义了你的 SELECT
,因为这是 Illuminate\Database\Eloquent\Builder@get
的定义:
public function get($columns = ['*'])
英文:
You have to select the user_id
field from pages
. That is the field that is used to then get the Users associated with all the Pages that the query would return. It is separate queries. How can Eloquent do a query to get all the Users that the Posts belong to if there is no user_id
field to use?
Page::with('user:id,name')->get(['title', 'body', 'user_id']);
This would mean all the returned Page results/objects would have a user_id
column that it can then pluck from the Collection to then do a query to load all the Users and then match them back to their parents.
The get
method is defining your SELECT
, as this is the definition of Illuminate\Database\Eloquent\Builder@get
:
public function get($columns = ['*'])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论