kylemilloy
1 week ago
121
12
Eloquent

Many-to-many only works one way

Posted 1 week ago by kylemilloy

I'm sure this is an error in my code somewhere that's filtering it out but I'm completely stuck. I have a vendors table and a products table that have a price associated with them in my product model doing the following:

class Product {
  vendors() {
    return $this->belongsToMany(Vendor::class)
      ->withPivot(['price'])
  }
}

class Vendor {
  products() {
    return $this->belongsToMany(Product::class)
      ->withPivot(['price'])
  }
}

When I call Vendor::first()->products() it returns all the products attached as expected. However on the Product model it returns an empty collection. Some products return their appropriate vendors but others do not. Is there a way I can debug the SQL queries being called so I can figure out where the problem is?

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