Axel
Axel

Reputation: 5111

How to set relation in laravel with two ids?

I have these two tables:

product
- id
- name

favorites
- id
- product_id
- user_id

So, a user can add product to favorites only once. How can I set up this relation something like the following?

public function favorites() {
    return $this->hasOne(Favorite::class, 'user_id', 'product_id')
}

So, I want to use both product_id & user_id such that the query would return proper result as per the following:

Get me the wishlist of user with id 1 and product with id 13!

Upvotes: 0

Views: 908

Answers (3)

user10186369
user10186369

Reputation:

You should try this:

Favorites Model

public function product(){
 return $this->belongsTo('App\Product','product_id');
}
public function user(){
 return $this->belongsTo('App\User','user_id');
}

Upvotes: 1

zjbarg
zjbarg

Reputation: 679

The user may have many favorites, so in Class User

public function favorites()
{
    return $this->hasMany('App\Favorite');
}

Class Favorite

public function product()
{
    return $this->belongsTo('App\Product');
}
public function user()
{
    return $this->belongsTo('App\User');
}

If you have user you can

$userFavProducts = $user->favorites;

$product2 = $user->favorites()->where('product_id', 2)->get();

Upvotes: 1

Naveed Ali
Naveed Ali

Reputation: 1045

you can do something like that:

in favourite Model class:

public function product(){
 return $this->belongsTo('App\Product');
}
public function user(){
 return $this->belongsTo('App\User');
}

In Product Model Class:

public function favorites(){
 return $this->hasMany('App\Favorite');
}

In User Model Class:

public function favorites(){
 return $this->hasMany('App\Favorite');
}

Upvotes: 1

Related Questions