Php Laravel-获取关系中的选定列

Php Laravel-获取关系中的选定列,php,laravel,eloquent,Php,Laravel,Eloquent,我一直在尝试使用laravel关系仅获取选定的列。 主表: posts - id - author_id - content post_media - id - post_id - link - caption 在我的laravel Post模型中,我定义了如下关系: public function postMedia() { return $this->hasMany(PostMedia::class); } 在获取数据时,查询是: Post::select('id', 'c

我一直在尝试使用laravel关系仅获取选定的列。 主表:

posts
- id
- author_id
- content
post_media
- id
- post_id
- link
- caption
在我的laravel Post模型中,我定义了如下关系:

public function postMedia()
{
    return $this->hasMany(PostMedia::class);
}
在获取数据时,查询是:

Post::select('id', 'content')
 ->with('postMedia:id,link')
 ->where('author_id', '=', auth()->user()->id)
 ->paginate();
但即使将
paginate()
替换为
get()
我也试过,

Post::select('id', 'content')
 ->with(['postMedia' => function ($query) {
  $query->select('id', 'link')
 })
 ->where('author_id', '=', auth()->user()->id)
 ->paginate();
但还是不起作用。我错过什么了吗?
谢谢。

您的查询应该是这样的:

$posts = Post::with(['postMedia' => function($query) {
             return $query->select(['id', 'link']);
         }])
         ->where('author_id', auth()->user()->id)
         ->select('id', 'content')
         ->get();

dd($posts)

您需要选择关系使用的键,否则它将无法将记录匹配回父项,在这种情况下,您还需要选择
post\u id
,外键:

Post::select('id', 'content')
    ->with('postMedia:id,link,post_id')
    ->where('author_id', '=', auth()->user()->id)
    ->paginate();
使用此功能时,应始终在要检索的列列表中包括
id
列和任何相关外键列


外键将根据表名自动计算。如果我使用带('postMedia')的->获取所有值,它会起作用,但当我试图从该表中获取特定列时,它不会起作用。@SwapnilBhikule确定。尝试获取特定列时是否发生错误?@SwapnilBhikule我已更新答案,请检查。此技巧对我有效,除了没有缩写形式,如
post\u media:id,post\u id,link
,这一个给了我一个SQL错误,表示
未知列post\u media.post\u id
。所以我不得不使用闭包来选择列的长形式。post_media上的外键的名称是什么?