gpt4 book ai didi

php - Laravel 存储库模式添加查询

转载 作者:可可西里 更新时间:2023-10-31 23:45:00 26 4
gpt4 key购买 nike

我正在 Laravel 中创建一个存储库模式,并且我创建了一个 AbstractRepository 类,它可以被任何存储库扩展以获得最常用的可以共享的 CRUD 方法。

现在,如果我需要一些更复杂的查询,我可以通过向具体存储库添加额外的方法来扩展主要功能。

例如:

public function eagerWhere($column, $value, $relation, $orderBy = 'name')
{
return Region::with($relation)->where($column, $value)->orderBy($orderBy);
}

现在我遇到麻烦的部分是使用我的存储库的主要代码中的这一部分:

$regions = $this->regionRepository->eagerWhere('name', $term, 'country');


if ($includeCountry) { //<-- from here
$regions->orWhereHas('country', function ($query) use ($term) {
$query->where('name', 'LIKE', '%' . $term . '%');
});
}

如何在存储库中编写该部分,以便最终使它看起来像:

$regions = $this->regionRepository->eagerWhere('name', $term, 'country');


if ($includeCountry) {
$regions->orWhereHas($term, 'country');
}

我尝试将那部分代码复制到存储库,但后来我无法链接方法,因为当获取 $region 时,它不再被视为存储库实例,而是 Eloquent 一。现在它期待 Eloquent 方法。

最佳答案

我认为您的抽象级别有点复杂,因为您并没有同时抽象模型本身,但无论如何。解决方案可能是这样的:

public function eagerWhere($column, $value, $relation)
{
$builder = Region::with($relation)->where($column, $value);

return $builder
}

然后:

$regions = $this->regionRepository->eagerWhere('name', $term, 'country');


if ($includeCountry) {

$regions->orWhereHas($term, 'country');
}

return $regions->orderBy('name')->get();

关于php - Laravel 存储库模式添加查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47881671/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com