如何访问laravel灯塔关系中的父作用域?



Laravel lighthouse不像eloquent那样访问关系范围。

class Tenant extends Model
{
public function products(): HasMany
{
return $this->hasMany(Product::class);
}

public function activeProducts(): HasMany {
return $this->products()->whereHas('templates', function (Builder $query) {
$query->where('id', $this->menu_template_id);
});
}
}

class Product extends Model
{
public function templates(): BelongsToMany
{
return $this->belongsToMany(MenuTemplate::class, 'menu_template_product');
}
}

这:$tenant = Tenant::find(1); dump($tenant->activeProducts);正在生产:

select * from `products` where `products`.`tenant_id` = 1 and `products`.`tenant_id` is not null and exists (select * from `menu_templates` inner join `menu_template_product` on `menu_templates`.`id` = `menu_template_product`.`menu_template_id` where `products`.`id` = `menu_template_product`.`product_id` and `id` = 1)

正确。

但是当我在graphql中调用相同的关系时,我得到以下查询:

select * from `products` where `products`.`tenant_id` = 1 and `products`.`tenant_id` is not null and exists (select * from `menu_templates` inner join `menu_template_product` on `menu_templates`.`id` = `menu_template_product`.`menu_template_id` where `products`.`id` = `menu_template_product`.`product_id` and `id` is null)

是相同的查询,但不是id = 1生成id is null。在灯塔$this->menu_template_idwhereHas()为空

TLDR: laravel lighthouse不能访问whereHas()中的$this

创建一个视图并将其用作ActiveProduct模型。

像这样:

CREATE VIEW active_products AS
SELECT 
*
FROM
`products`
WHERE
`products`.`tenant_id` IS NOT NULL
AND EXISTS( SELECT 
*
FROM
`menu_templates`
INNER JOIN
`menu_template_product` ON `menu_templates`.`id` = `menu_template_product`.`menu_template_id`
WHERE
`products`.`id` = `menu_template_product`.`product_id`
AND `menu_templates`.`id` = `products`.`menu_template_id`)

相关内容

  • 没有找到相关文章

最新更新