LDUBBS
LDUBBS

Reputation: 603

Attaching extra model to BelongstoMany relations

I have two tables (users and drinks) with a pivot table, the user has a hasOne relation with profiles table, is there a way to attach the profile table to the pivot table and get all data.

Table user

id | name | email

Table profile

id | user_id | picture

Table drinks

id | name | price

Pivot Table user_drinks

id | user_id | drink_id | quantity | price | status

Drink Model

public function users()
{
   return $this->belongsToMany('App\User', 'user_drinks', 'drink_id', 'user_id')->withPivot('price', 'quantity')->withTimestamps();
}

User Model

public function drinks()
{
   return $this->belongsToMany('App\Drink', 'user_drinks', 'drink_id', 'user_id')->withPivot('price', 'quantity')->withTimestamps();
}

public function profile() {
         return $this->hasOne('App\Profile');
     }

PS: I don't wanna write this with raw sql query, it's driving me nuts.

Upvotes: 2

Views: 72

Answers (1)

Professor
Professor

Reputation: 908

I wouldn't change the tables relation. I'd use the ->with() function to get the profile information within the existing relations.

So $user->drinks()->where('drink_id', $drink_id)->with('profile')->get(); would be my guess.

Upvotes: 5

Related Questions