JoaquinVilchez
1 week ago
189
9
Laravel

Relationship Many to Many returns 1

Posted 1 week ago by JoaquinVilchez

Hello, I am wanting to make a many to many relationship as I have always done but it only returns a 1 when I invoke it.

I followed the steps of the documentation but I could not get a result.

What I have are products that can have variants, such as 1kg of ice cream has different tastes and tastes can be in many products (Ice cream 500g, etc.)

I show you what I do:

In Product.php

class Product extends Model
{
    public function variants(){
        return $this->belongsToMany(Variant::class, 'products_variants');
    }
}

In Variant.php

class Variant extends Model
{
    public function products(){
        return $this->belongsToMany(Product::class, 'products_variants');
    }
}
 $products = $restaurant->products()->where('temporary',false)->where('state', '!=', 'removed')->orderBy('category_id', 'asc')->get();

        foreach($products as $product){
            dump($product->variants);
        }

	die();

Here it returns me, in case it has variants, a 1, if not I return 0.

On the other hand, if I want to show the products that are related to a particular variant, if it shows me the products objects.

$variant->products;

Thank You!

Please sign in or create an account to participate in this conversation.