首页 > 解决方案 > 在第二次调用中雄辩地复制绑定

问题描述

我在 Laravel 项目中使用 Reposity 模式。问题是我看到它在第二个调用查询中复制了绑定!

这是我的代码:

class AirController extends Controller
{
    private $airportService;

    public function __construct(AirportService $airportService) {
        $this->airportService = $airportService;
    }

    public function getAirports(){
        $departure_airport = $this->airportService->getCityFromAirport("6");
        $destiny_airport = $this->airportService->getCityFromAirport("10");
    }
}

调试,$departure_airport获取记录,但$destiny_airport失败。你会觉得id: 10有问题。没有。如果我交换并$destiny_airport放在第一位,它会获得记录,但随后$departure_airport失败。然后,我考虑按照此处的建议打印原始 SQL 查询。

这是结果

INFO: "select * from `airports` where `airports`.`id` = ? limit 1"  
INFO: ["6"]  
INFO: "select * from `cities` where `cities`.`id` = ? limit 1"  
INFO: [441]  
*****************************************************************************************
INFO: "select * from `airports` where `airports`.`id` = ? and `airports`.`id` = ? limit 1"  
INFO: ["6","10"]

为什么在第三个查询中(在星号之后)当我在第二个查询中仅将 10 作为参数传递时,使用参数 6 和 10 复制列“id”?!而不是第三个查询,我希望它是这样的:

INFO: "select * from `airports` where `airports`.`id` = ? limit 1"  
INFO: ["10"]

这是实现:

机场服务.php

use App\Repositories\AirportRepository as Airport;

class AirportService {

    private $airport;

    public function __construct(Airport $airport){
        $this->airport = $airport;
    }

    public function getCityFromAirport($airportId){
        $airport = $this->airport->find($airportId);
        return $airport->City;
    }
}

存储库.php

...

public function find($id, $columns = array('*')) {
    return $this->model->find($id, $columns);
}

...

IRepository.php

...

public function find($id, $columns = array('*'));

...

给出的错误是:

local.ERROR: Trying to get property of non-object {"userId":41,"email":"...@...","exception":"[object] (ErrorException(code: 0): Trying to get property of non-object at C:\\wamp\\www\\project\\API\\app\\Services\\AirportService.php:21)

标签: phplaravelbindingeloquentrepository-pattern

解决方案


尝试调用newModelInstance存储库的 find 方法。

return $this->model->newModelInstance()->find($id, $columns);

推荐阅读