Mohan
Mohan

Reputation: 4829

Eloquent Model for pivot table with 3 foreign keys?

I am working on a project with has this kind of an model.

A vendor's table to store all vendor details - A vendor is like a company that offers some service.

vendor

id  | name
----+-------
 1  | abc 
 2  | def

Then I have a Services table which contains the list of all the services that a vendor can offer:

service

id | name
---+----------------
1  |  abc
2  |  def
3  |  ghi

And there is an area table which contains the list of all the areas from which vendor's can chose if they want to provide service in that area or not.

Areas

id | name
---+------
1  | abc
2  | def
3  | ghi

Now I want to have a pivot table that stores the details of which vendor provides which service in which area and at what price so my pivot table structure is like this:

vendor_id  | service_id | area_id | price 
-----------+------------+---------+---------
   1       |    1       |    2    |   25.00
   1       |    1       |    1    |   24.00
   2       |    1       |    1    |   23.00

and so on ...

So, now I have 3 different eloquent models for areas services and vendors; however, as the pivot table contains 3 foreign keys, I am unable to update the pivot table properly each time a vendor changes his preferences.

Can you please suggest me the way to define relationship in this scenario or should I change my table structure to store this data?

Upvotes: 3

Views: 4931

Answers (2)

Nick Howarth
Nick Howarth

Reputation: 634

I ran into this issue today.

You can use the syncWithPivotValues() method, passing the extra foreign key(s).

$vendor->services()->syncWithPivotValues($service_id, ['area_id' => $area->id])

https://laravel.com/docs/8.x/eloquent-relationships#syncing-associations

Upvotes: 1

Syed Rizwan Ali
Syed Rizwan Ali

Reputation: 233

The following article from 2013 did the job for me.

http://developed.be/2013/08/30/laravel-4-pivot-table-example-attach-and-detach/

The setup is something like below

Users
id | name | email

Projects
id | title | details

Roles
id | title

Project_User
id | project_id | user_id | role_id

class Project extends Eloquent
{
    public function users(){
        return $this->belongsToMany('User','project_user','project_id','user_id')
            ->withPivot('role_id')
            ->join('roles','role_id','=','roles.id')
            ->select('roles.title as pivot_roles_title');
    }
}

Upvotes: 1

Related Questions