【发布时间】:2020-10-27 10:31:22
【问题描述】:
我开发了一个package to enable search method on Eloquent models with JSON。
引擎目前的工作方式是根据提供的值附加查询以获取支持的参数。
Builder::macro('search', function (Request $request) {
/**
* @var $this Builder
*/
$searcher = new Searcher($this, $request);
$searcher->search();
return $this;
});
依次运行以下内容:
/**
* Perform the search
*
* @throws Exceptions\SearchException
*/
public function search(): void
{
$this->appendQueries();
Log::info('[Search] SQL: ' . $this->builder->toSql());
}
/**
* Append all queries from registered parameters
*
* @throws Exceptions\SearchException
*/
protected function appendQueries(): void
{
foreach ($this->requestParametersConfig->registered as $parameter) {
$requestParameter = $this->createRequestParameter($parameter);
$requestParameter->appendQuery();
}
}
protected function createRequestParameter($parameter): AbstractParameter
{
return new $parameter($this->request, $this->builder, $this->modelConfig);
}
请求参数在配置文件中注册并指向请求参数类以使所有内容模块化。
现在,如果在index 端点或自定义search 端点上使用它会很好,但我也想将功能扩展到show。问题在于,使用路由模型绑定时,模型在我获取它时已经加载。
让我们以关系为例。我有一个请求参数,在使用时会在给定模型上加载关系:
www.example.com/api/contacts?relations=(phones)
将通过这样做在Contact 模型上加载phones 关系:
/**
* Append the query to Eloquent builder
* @throws SearchException
*/
public function appendQuery(): void
{
$arguments = $this->getArguments();
$this->builder->with($arguments);
}
但是当我在已经加载的模型上执行->with 后跟->get() 时,我只会得到所有具有加载关系的模型的列表。
有没有办法用查询构建器“利用”已经加载的模型,或者此时它已经完成了交易,我应该在show 路由上获取 ID 而不是解析它,然后组装查询?
【问题讨论】:
标签: php laravel package laravel-7