我有两个表,User和Post。一个用户可以有多个帖子,一个帖子只能属于一个用户。

在我的用户模型中,我有一个hasMany关系…

public function post(){
    return $this->hasmany('post');
}

在我的post模型中,我有一个belongsTo关系…

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

现在我想使用Eloquent with()连接这两个表,但想要第二个表中的特定列。我知道我可以使用查询生成器,但我不想这样做。

在Post模型中,我写…

public function getAllPosts() {
    return Post::with('user')->get();
}

它运行以下查询…

select * from `posts`
select * from `users` where `users`.`id` in (<1>, <2>)

但我想要的是…

select * from `posts`
select id,username from `users` where `users`.`id` in (<1>, <2>)

当我用…

Post::with('user')->get(array('columns'....));

它只返回第一个表中的列。我想要第二个表中使用with()的特定列。我该怎么做呢?


当前回答

如果你使用php7.4或更高版本,你也可以使用箭头函数,这样看起来更干净:

Post::with(['user' => fn ($query) => $query->select('id','username')])->get();

其他回答

如果你想在laravel eloquent中使用with()获得特定的列,那么你可以使用下面的代码,这最初是由@Adam在他的回答中回答这个相同的问题,答案的主要代码如下所示:

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

所以我在我的代码中使用了它,但它给了我1052的错误:字段列表中的列“id”是不明确的,所以如果你们也面临同样的问题

然后为了解决这个问题,你必须在with()方法的id列之前指定表名,如下所示:

Post::with('user:user.id,username')->get();

注意,如果你只需要表中的一列,那么使用'lists'是非常好的。在我的情况下,我正在检索用户最喜欢的文章,但我只想要文章id的:

$favourites = $user->favourites->lists('id');

返回一个id数组,例如:

Array
(
    [0] => 3
    [1] => 7
    [2] => 8
)

在Laravel 5.7中,你可以像这样调用特定的字段

$users = App\Book::with('author:id,name')->get();

在选择中添加foreign_key字段是很重要的。

您还可以在访问相关模型时指定该模型的列。

::第一()- >用户()- >((“列…”));

您可以试试这段代码。在laravel 6版本中进行了测试。

Controller code
 public function getSection(Request $request)
{

  Section::with(['sectionType' => function($q) {
      $q->select('id', 'name');
  }])->where('position',1)->orderBy('serial_no', 'asc')->get(['id','name','','description']);
  return response()->json($getSection);
}
Model code
public function sectionType(){
    return $this->belongsTo(Section_Type::class, 'type_id');
}