簡體   English   中英

用方法選擇laravel eloquent中的特定列

[英]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')

https://laravel.com/docs/5.6/collections#method-pluck

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM