Laravel幽默。将投影添加到相关模型

时间:2019-04-09 08:38:42

标签: laravel jenssegers-mongodb moloquent

我有一个与关系有关的查询。

$dbQuery = $this->someModel
    ->where('user_id', '<>', Auth::id())
    ->with(['questions'])
    ->get(['title', 'status', 'expired_at']);

get()方法中的字段列表定义了所选数据顶层的所选字段列表。但是我还需要为questions关系添加一个投影。如何仅选择questions._idquestions.description

我已尝试将其添加到get()列表中,但这种方式不起作用。

2 个答案:

答案 0 :(得分:3)

您可以对with使用闭包来仅选择某些列:

Model1::with(['model2' => function($query){
    $query->select('column1','column2');
}])->get();

答案 1 :(得分:0)

我已经找到了一个基于@namelivia答案的解决方案。现在,它适用于select,但适用于project

Model1::with(['model2' => function($query){
    $query->project([
        'column1' => 1,
        'column2' => 1,
        'foreign_key' => 1 /* can not be excluded. */         
    ]);
}])->get();