提问者:小点点

使用Laravel Eloquent进行子查询以检索属性的答案


我有两张桌子。

属性
id,team_id,type_id,name,group

answers_attributes
id,name,person_id,attribute_id

我不能修改数据库的结构。 我想检索带有其答案的当前团队的属性列表。

为此,我正在寻找一种组合两个查询的方法。

我想先得到属性列表。 然后,使用每个属性的ID,检索其对应的答案。

我曾尝试在一个SQL请求中完成此操作,但不可能。

$data = Attribute::where([
            ['type_id', $type_id],
            ['group', $group],
            ['team_id', Auth::user()->currentTeam->id]
        ])->addSelect(['answer' => function($query) {
            $query->select('name')
                ->from('answers_attributes')
                ->whereColumn('attribute_id', 'attributes.id')
                ->first();
        }])->orderBy('name', 'ASC')->get();

你有什么主意吗?

谢谢


共1个答案

匿名用户

可以使用子查询选择

$data = Attribute::where([
            ['type_id', $type_id],
            ['group', $group],
            ['team_id', Auth::user()->currentTeam->id]
        ])->addSelect(['answer' => AnswerModel::select('name')
                ->whereColumn('attribute_id', 'attributes.id')
                ->limit(1)])->orderBy('attributes.name','ASC')->get();

这里我有两个注意事项:

1-用得到的答案模型替换“AnswerModel”。

2-在order by子句中,确保将表名写在列名'name'之前,因为您有两列名为'name'(在attributes和answers_attributes表中)