[英]Select specific column in laravel eloquent's with method
我正在使用laravel 5.6
,我希望獲得帶有comments
用戶posts
(僅限id
字段)
用戶模型
public function posts()
{
return $this->hasMany('App\Post');
}
發布模型
public function user()
{
return $this->belongsTo('App\User');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
評論模型
public function post()
{
return $this->belongsTo('App\Post');
}
在我的控制器中,我使用此代碼來獲取用戶帖子的評論
$posts = $request->user()->posts()->with(['comments' => function($query) {
$query->select(['id']);
}]);
但它不起作用......
當我評論$query->select(['id']);
它工作正常,但返回所有字段的Comment
模型。 我只想選擇id
字段。
我在這里缺少什么?
您還必須選擇外鍵列(匹配結果所需):
$posts = $request->user()->posts()->with('comments:id,post_id');
如果你只想要一列,你可以使用->pluck('id')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.