我在Laravel项目中使用存储库模式。问题是我看到它正在第二个调用查询中复制绑定!
这是我的代码:
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
会失败。然后,我考虑按照建议的here打印原始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"]
这是实现:
AirportService.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;
}
}
Repository.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)
答案 0 :(得分:1)
尝试在存储库的find方法中调用newModelInstance
。
return $this->model->newModelInstance()->find($id, $columns);