Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using name column in belongsToMany relation instead of id

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.
}
like image 615
Amarjit Singh Avatar asked Jan 24 '18 09:01

Amarjit Singh


2 Answers

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)

like image 182
Ahmed Essam Avatar answered Sep 17 '22 14:09

Ahmed Essam


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.

like image 24
Alexey Mezenin Avatar answered Sep 16 '22 14:09

Alexey Mezenin