0

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.

grimdbx
  • 175
  • 2
  • 12

1 Answers1

0

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`)
  • I'm not sure I understand how. Can you please edit your answer with an example? – grimdbx May 08 '22 at 07:07
  • I mean: - create a MySQL view to get tenant active products - create a model like TenantsActiveProduct - add a relation to the Tenant model – Vadym Selian May 09 '22 at 10:19