如何从预加载中指定我们想要的列
How to specify columns we want from eager load
我正在使用 beyondcode/laravel-comments (https://github.com/beyondcode/laravel-comments),我尝试指定我想从评论员那里获得的列。这是代码:
$comment = $post->comments()->with('commentator', function ($query) {
$query->select('commentator.name', 'commentator.email');
//or $query->select('users.name', 'users.email');
})->latest();
我收到这样的错误
Undefined table: 7 ERROR: missing FROM-clause entry for table "commentator" // or users
我该如何解决?谢谢
As in the documentation,只需像这样执行您的预加载以指定列,不需要函数:
$comment = $post
->comments()
->with('commentator:id,name,email')
->latest();
如果您确实需要使用回调来改变预加载,则必须使用数组 in the documentation:
$comment = $post
->comments()
->with([
'commentator' => fn ($q) => $q->select('id', 'name', 'email')
])
->latest();
$comment = $post->comments()->with('commentator:primary_key,your_column_name')->latest();
使用此功能时,您应始终在要检索的列列表中包含 ID 列和任何相关的外键列。
我正在使用 beyondcode/laravel-comments (https://github.com/beyondcode/laravel-comments),我尝试指定我想从评论员那里获得的列。这是代码:
$comment = $post->comments()->with('commentator', function ($query) {
$query->select('commentator.name', 'commentator.email');
//or $query->select('users.name', 'users.email');
})->latest();
我收到这样的错误
Undefined table: 7 ERROR: missing FROM-clause entry for table "commentator" // or users
我该如何解决?谢谢
As in the documentation,只需像这样执行您的预加载以指定列,不需要函数:
$comment = $post
->comments()
->with('commentator:id,name,email')
->latest();
如果您确实需要使用回调来改变预加载,则必须使用数组 in the documentation:
$comment = $post
->comments()
->with([
'commentator' => fn ($q) => $q->select('id', 'name', 'email')
])
->latest();
$comment = $post->comments()->with('commentator:primary_key,your_column_name')->latest();
使用此功能时,您应始终在要检索的列列表中包含 ID 列和任何相关的外键列。