“Laravel”的“with”方法目前无法与“get”方法一起使用。

huangapple go评论55阅读模式
英文:

Laravel "with" does not work currently next to "get" method

问题

Laravel中withget方法旁边带有参数时目前不起作用。

我有两个具有一对多关系的表格。
“Laravel”的“with”方法目前无法与“get”方法一起使用。

我编写了这段代码:

Page::with('user:id,name')->get();

“Laravel”的“with”方法目前无法与“get”方法一起使用。

目前这段代码可以正常工作,但我想要从pages表中获取特定列(例如titlebody),所以我编写了这段代码:

Page::with('user:id,name')->get(['title', 'body']);

user将为null

“Laravel”的“with”方法目前无法与“get”方法一起使用。

英文:

Laravel with does not work currently next to get method when get has argument

I have two table that has one-to-many relationship.
“Laravel”的“with”方法目前无法与“get”方法一起使用。

I wrote this code:

Page::with('user:id,name')->get();

“Laravel”的“with”方法目前无法与“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

“Laravel”的“with”方法目前无法与“get”方法一起使用。

答案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 = ['*'])

huangapple
  • 本文由 发表于 2023年4月10日 20:09:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75976988.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定