I have two Models one is Offer (for offers table) and other is Brand (for brands table). There is a "many to many" relationship between these models.
I have a table offer_brands that maps the relation between these two tables. In this table, I have offer_id column that links this table to offers table and brand column that links this table to the brands table usind brand_name column in brands table.
In Brand Model I want a relation that return all the offers.
I know I can do it like
public function offers()
{
return $this->belongsToMany(Offer::class, 'offer_brands', 'offer_id', 'brand_id'); // But don't have brand_id column insted I have brand column that contains brand names
}
Also, I have tried
public function offers()
{
return $this->belongsToMany(Offer::class, 'offer_brands', 'offer_id', 'brand'); // But Eloquent compare this column with id column of brands table.
}
Just in case if someone still looking for an answer .. here's how you can solve this issue.
For example I have roles for users. and the pivot table (team_users
) has the user_id
. But instead of containing the role_id
it contains role
column which basically is the slug
of the role in roles
table.
I can specify the relation exactly like this:
public function roles()
{
return $this->belongsToMany('App\Role', 'team_users', 'user_id', 'role', 'id', 'slug');
}
Basically App\Role
is the relation model.
team_users
is the pivot table name.
user_id
is the foreign pivot key (So in team_users
there will be a column called user_id
)
role
is the related pivot key (So in team_users
there will be a column called role
)
id
is the parent key (So in App\User
Laravel will look for the row whose id
column value equals the foreign pivot key user_id
in the pivot table).
slug
is the related key (So in App\Role
Laravel will look for the row whose slug
column value equals role
column in the pivot table)
The correct definition:
return $this->belongsToMany(Offer::class, 'offer_brands', 'brand', 'offer_id');
But it's a good idea to use naming conventions. You could name the table brand_offer
and foreign keys as offer_id
and brand_id
. In this case, the relationship would look like this:
return $this->belongsToMany(Offer::class);
Learn more about Laravel naming conventions in my best practices repo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With