在Laravel中调用同一类的多个方法



我一直很好奇Laravel的雄辩是如何工作的,以及他们是如何在同一行代码中传递许多方法的。示例:auth()->user()->where(...)->get()在这个例子中,他们使用两种方法";其中";以及";得到";因此,我尝试创建以下存储库:

class SkillKeyRepository
{
protected $model;
/**
* @param SkillKey $model
*/
public function __construct(SkillKey $model)
{
$this->model = $model;
}
public function all(array $column = []): Collection
{
return $this->model::all($column);
}
public function where($column, $attribute): SkillKeyRepository
{
$this->model::where($column, $attribute);
return $this;
}
public function get()
{
return $this->model::get();
}
}

之后,在我的服务,我尝试了以下:

class SkillKeyService
{
use ServiceTrait;
protected $repository;
/**
* @param SkillKeyRepository $repository
*/
public function __construct(SkillKeyRepository $repository)
{
$this->repository = $repository;
}
public function get()
{
dd($this->repository->where('key', 'TagName')->get());
}

正确的结果应该是一个项目的集合。但它从数据库返回所有数据,并忽略where((函数,直接转到get((函数。

问题是使用模型创建查询,然后尝试使用原始模型添加newQuery方法将更多链接到查询

class SkillKeyRepository
{
protected $query;
/**
* @param  SkillKey  $model
*/
public function __construct(SkillKey $model)
{
$this->query = $model->newQuery();
}
public function all(array $column = []): Collection
{
return $this->query::all($column);
}
public function where($column, $attribute): SkillKeyRepository
{
$this->query::where($column, $attribute);
return $this;
}
public function get()
{
return $this->query::get();
}
}

问题是您正在使用模型来创建一个查询,然后尝试使用原始模型将更多的查询链接到查询,但这不起作用,因为您需要以前生成的查询。

最简单的方法是实际返回查询生成器对象本身:

class SkillKeyRepository
{
protected $model;
/**
* @param SkillKey $model
*/
public function __construct(SkillKey $model)
{
$this->model = $model;
}
public function all(array $column = []): Collection
{
return $this->model->all($column);
}
public function where($column, $attribute): QueryBuilder
{
return $this->model->newQuery()->where($column, $attribute);
}
}
(new SkillKeyRepository(new SkillKey()))->where('a','b')->get(); // Should work

然而,你真的应该退一步,重新考虑你在做什么。Laravel已经有了查询构建器对象来实现这一点,你为什么要重新编写它?

最新更新