It seems like you're on the right track with setting up a many-to-many relationship using Eloquent. However, there might be a small issue with the way you've defined the relationship in your Quotation model. Let's go through the steps to ensure everything is set up correctly.
First, ensure that your pivot table product_quotation has the correct foreign key column names that match the primary keys in the related tables. Based on your description, the pivot table should have product_id and reference as foreign keys.
Next, let's define the relationships in both the Product and Quotation models. Since you've mentioned custom primary keys, you'll need to specify these keys in the relationship methods.
Here's how you should define the relationship in your Quotation model:
class Quotation extends Model
{
// If your primary key is not 'id', specify it here
protected $primaryKey = 'reference';
public function products()
{
// Assuming 'product_quotations' is the pivot table name
// 'reference' is the foreign key name in the pivot table for the Quotation model
// 'product_id' is the foreign key name in the pivot table for the Product model
return $this->belongsToMany(Product::class, 'product_quotations', 'reference', 'product_id');
}
}
And here's how you should define the inverse relationship in your Product model:
class Product extends Model
{
// If your primary key is not 'id', specify it here
protected $primaryKey = 'product_id';
public function quotations()
{
// The order of keys is the inverse of the Quotation model
return $this->belongsToMany(Quotation::class, 'product_quotations', 'product_id', 'reference');
}
}
Now, when you want to retrieve the products related to a quotation, you should use the relationship method you've defined (products), not product. Here's how you can do it in Tinker:
$quote = App\Models\Quotation::first();
$products = $quote->products; // Use the relationship method 'products', not 'product'
If you still encounter issues, make sure that:
- The
product_quotationspivot table contains the correct data with matchingproduct_idandreferencevalues. - The
ProductandQuotationmodels are in the correct namespace if you're using namespaces. - You've run
composer dump-autoloadif you've made changes to the class names or locations to ensure the autoloader is up to date.
If you've checked all of these and it's still not working, please provide more details about the error messages or unexpected behavior you're encountering.