Laravel子查询在使用嵌套时不会删除结果



我有一个"用户"表,其中包含用户提供的服务的数据透视表:

// AppUser
public function services()
{
return $this->hasMany('AppServiceUser');
}

在 ServiceUser 模型上,我有另一个关系来获取服务信息:

public function service() 
{
return $this->hasOne('AppService', 'id');
}

当获取团队(使用Laravel Spark(时,我使用的查询是:

Team::with('users')->withUserCustomerServices()->where('id', $teamId)->first();

此查询的范围在团队模型中:

public function scopeWithCustomerServices($query)
{
$query = $query;
$query->with('users.services');
$query->with(['users.services.service' => function($q) {
$q->where('visible_to_customers', 1);
}]);
return $query;
}

输出时(使用 Vue.js(:

{{ user.services.length }}

我得到(在本例中(返回 6 个结果。但是,其中一个服务的数据库字段"visible_to_customers"设置为 0。

最初我认为我的查询会按预期工作并且只返回 5 个服务,但它实际上仍然返回所有服务,但如果字段为 0,则不返回关系(服务(。

如何仅返回关系具有特定字段值的数据透视表结果?

编辑

我已经更新了查询以在第一个嵌套关系上使用wherehas:

$query->with(['users.services' => function($q) {
$q->whereHas('service', function($q) {
$q->where('visible_to_customers', 1);
});
}]);

这很好用,仅返回数据透视表行,其中服务表的字段值为 1 表示visible_to_customers。

但是,这不会获取相关行本身。

如果我接着说:

$query->with(['users.services' => function($q) {
$q->whereHas('service', function($q) {
$q->where('visible_to_customers', 1);
});
}]);
$query->with(['users.services.service' => function($q) {
$q->where('visible_to_customers', 1);
}]);

它仍然是相同的问题,它获取所有行,但仅获取字段为 1 的相关行。

通过在作为透视的第一个关系上使用 where 有来解决此问题:

$query->with(['users.services' => function($q) {
$q->whereHas('service', function($q) {
$q->where('visible_to_customers', 1);
})->with('service');
}]);

然后我将 ->with('service'( 附加到链的末尾。

最新更新