gpt4 book ai didi

laravel - Eloquent (Laravel 5) - 如何在关系查询 (whereHas) 中包含 SoftDeleted 记录?

转载 作者:行者123 更新时间:2023-12-02 21:17:31 38 4
gpt4 key购买 nike

我使用 Eloquent 构建了一个存储库层。我在表之间有很多复杂的关系,并且能够使用 eloquent 轻松构建所有查询,我非常依赖WhereHas 查询来根据关系条件进行查询。

完成所有查询并工作后,最后要做的事情是在我的一些查询中添加一个包含软删除记录(在特定日期后删除)的选项 - 这突出了一些问题。

例如,我可能有一个查询,它通过急切加载必要的数据开始如下:

public function query()
{
$this->query = AssetInstance::with('asset.type', 'zoneInstance.type', 'zoneInstance.zone');
)

然后我可能有一个函数可以选择性地优化查询,如下所示:

function filterByZoneInstance($zone_instance_id)
{
$this->query->whereZoneInstanceId($zone_instance_id);
return $this;
}

我可能有另一个函数来进一步优化查询:

public function filterByZoneType($type)
{
$this->query->whereHas('zone_instance', function($q) use($type){
return $q->whereHas('type', function($q2){
return $q2->whereName($type);
});
});
}

public function get()
{
return $this->query->get();
}

所以这一切都很好,我可以这样做:$this->query()->filterByZoneType('typex')->get();

现在,假设我想包含 softDeleteResults,我可以这样做:

public function includeTrashed()
{
$this->query->withTashed();
return $this;
}

但这不会影响到关系,所以是的,所有 assetInstances(包括软删除都会被拉入),但不是所有 zoneInstances,如果关系(例如 zone_instance 已被软删除),这反过来会导致 filterByZoneType 失败.

所以我认为没问题 - 我可以用垃圾加载关系:

public function query()
{
$this->query = AssetInstance::with(['asset.type', 'ZoneInstance' => function ($q){
$q->withTrashed();
}, 'zoneInstance.type', 'zoneInstance.zone']);
)

这种方法一直有效,直到您应用 whereHas 查询,此时 withTrashed 的热切加载会被执行其自己的热切加载(没有垃圾)的 wherehas 查询覆盖;

我尝试在 whereHas 闭包中应用约束,但它不起作用:

public function filterByZoneType($type)
{
$this->query->whereHas('zone_instance', function($q) use($type){
return $q->whereHas('type', function($q2){
return $q2->whereName($type)->withTrashed();
})->withTrashed();
});
}

我此时决定使用原始查询,不幸的是,这具有类似的效果,因此,例如,如果我执行以下操作:

$this->query->whereRaw("asset_instances.`deleted_at` <= '2014-03-11 00:00:00' and (select count(*) from `variable_data_package_instances` where `variable_data_package_instances`.`asset_instance_id` = `asset_instances`.`id` and `variable_data_package_instances`.`deleted_at` <= '2014-03-11 00:00:00')");

我现在看到的是,废弃的 zoneInstances 不再急切加载(从之前调用的 query() 函数)。

有人有幸使用 Eloquent 关系查询来带来垃圾结果吗?

最佳答案

这个怎么样:

public function query()
{
$this->query = AssetInstance::with(['asset.type', 'ZoneInstance' => function ($q){
$q->withTrashed()->with('type','zone');
}]);
)->get();
}

关于laravel - Eloquent (Laravel 5) - 如何在关系查询 (whereHas) 中包含 SoftDeleted 记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29697756/

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