在 laravel 10 网站上从 Post 表发出请求(其中有很多列,我还得到了相关的创建者表:
$postList = Post
::orderBy('created_at', 'desc')
->with('creator')
->get();
我可以访问
$post->creator->name
场。我尝试使用字段列表减少请求的字段数量:
$postList = Post
::orderBy('created_at', 'desc')
->with('creator')
->select('id', 'title', 'slug', 'published', 'created_at')
但在这种情况下,我看到错误,因为 $post->creator 为空
在 sql - 跟踪中我看到列出的字段
SELECT `id`, `title`, `slug`, `published`, `created_at`
FROM `post`
ORDER BY `created_at` desc
是否有办法在 1 个请求中使用 >select(字段列表和关系?
"laravel/framework": "^10.48.4",
提前致谢!
当您加载关系时,您必须始终确保这些关系所依赖的模型确实已加载相关键。例如:
$postList = Post::select(
'id',
'creator_id', // fk to Creator model
'title',
'slug',
'published',
'created_at',
)
->with('creator:id,name,other_columns...') // now related creators can be matched
->latest()
->get();