Select 来自两个相关 tables/models 的特定列

Select specific columns from both related tables/models

我有 N x 1 的关系,Post x User,Post->用户有如下关系:

Post.php(型号):

....
public function user() {
    return $this->belongsTo('User');
}
....

当我提取每个 Post 时,我只想 select 来自用户模型的 idusername,但我也只想要 id和 Post 中的 title(不是 Post 模型中的每一列)。

With this solution:

return Post::with(array('user'=>function($query){
    $query->select('id','username');
}))->get();

我可以从 User 中获取 idusername,但我也从 Post 模型中提取所有列,这不是我想要的,所以 o 尝试过:

return Post::with(array('user'=>function($query){
    $query->select('id','username');
}))->select(['id', 'title'])->get();

虽然没有成功,但 User 变为空,我只剩下 Post 中的 idtitle

我将返回 json 回复,以防相关。

注意: 我不想在我的 Post.php 模型文件中添加任何内容 'hard coded',因为我可能需要相同的关系,不同的列用于不同的情况,所以我想保持关系在 Post.php

Post::select('id', 'title', 'user_id')
->with(array('user'=>function($query){
    $query->select('id','username');
}))->get();

您需要外键来维护两个模型之间的关系。

我通常是这样做的。

Post::select('id','title','user_id')->with('user:id,username')->get();

为此,您需要正确定义关系,并且必须 select 外键形成 post table 。