'How can I access parent scope in laravel lighthouse relationship?

Laravel lighthouse doesn't access relationship scope like 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');
        }
    }

This: $tenant = Tenant::find(1); dump($tenant->activeProducts); is producing :

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)

Which is correct.

But when I call the same relation in graphql I get the following query:

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)

Is the same query but instead of id = 1 is producing id is null. In lighthouse $this->menu_template_id from within the whereHas() is null

TLDR: laravel lighthouse cannot access $this in whereHas() on relationship.



Solution 1:[1]

Create a view and use it as an ActiveProduct model.

Something like this:

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`)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1