在Laravel中为子查询/联接查询自动插入表名(口才)

时间:2018-08-06 10:41:27

标签: laravel eloquent

这是我的查询:

PHP
public function find(array $filter = []) : Collection
{
return $this->entity::where($filter)->join('cases_has_services', function ($join) {

        $join->on('cases_has_services.cases_id', 'checklists.cases_id');
        $join->on('cases_has_services.services_id', 'checklists.item_id');

    })->select('checklists.*', 'cases_has_services.quantity')->get();

}

我收到下一个错误:

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where 
clause is ambiguous (SQL: select `checklists`.*, 
`cases_has_services`.`quantity` from `checklists` inner join 
`cases_has_services` on `cases_has_services`.`cases_id` = 
`checklists`.`cases_id` and `cases_has_services`.`services_id` = 
`checklists`.`item_id` where (`id` = 352))

所以我修正了我的代码:

public function find(array $filter = []) : Collection
{

    // TODO fix this
    foreach ($filter as $field => $value) {

        unset($filter[$field]);

        $field = 'checklists.' . $field;

        $filter[$field] = $value;

    }

    return $this->entity::where($filter)->join('cases_has_services', function ($join) {

        $join->on('cases_has_services.cases_id', 'checklists.cases_id');
        $join->on('cases_has_services.services_id', 'checklists.item_id');

    })->select('checklists.*', 'cases_has_services.quantity')->get();

}

但是我认为这不是一个好习惯。那么,是否有任何本地laravel路径可以在具有联接的查询中自动插入表名? 我的意思是,如何避免使用那部分代码,因为它有点hacky:

    foreach ($filter as $field => $value) {

        unset($filter[$field]);

        $field = 'checklists.' . $field;

        $filter[$field] = $value;

    }

1 个答案:

答案 0 :(得分:0)

将$ filter变量更改为:

$filter = ['checklists.id' => 123]