通过findMany选择列并在Laravel的Eloquent中保持关系

问题描述 投票:0回答:1

我正在努力获得帖子和作者。但是,我只需要帖子的标题和作者信息。

这是我正在运行的查询:

// I want post titles with IDs of 1, 2, 3, 4 and 5 and the author of each one
Post::with('author')->findMany([1, 2, 3, 4 , 5], ['post_title');

生成的集合具有post_title罚款,但作者关系为空。

但是,如果我跑:

Post::findMany([1, 2, 3, 4, 5])->with('author');

我可以访问$post->author->first_name中的作者。

如果我指定了我需要的列,我不明白为什么关系会丢失。

那么,如何查询posts表,指定我想选择哪些列并保持与作者的关系?

php laravel eloquent
1个回答
1
投票

你必须选择Post id,因为当你使用with方法时它意味着你正在使用Laravel Eager Loading,Eager Load需要Post id来加载author

Post::with('author')->findMany([1, 2, 3, 4 , 5], ['id','post_title');
© www.soinside.com 2019 - 2024. All rights reserved.