Reputation: 3074
Let me explain the actual case. I have three tables like:
Here shop_id
of product
table is the foreign key of shop
table. Again shop_owner_id
of shop table is foreign key of users table. Now I have product_id
and I want to get shop_owner_id
. I can do this as follows:
STEP 1. get `shop_id` from `product_id`
STEP 2. get `shop_owner_id` from `shop_id`
OR I can write a raw sql query to join these there table and get the shop_owner_id
from product_id
. But is there any descent way in laravel.
Upvotes: 0
Views: 145
Reputation: 5603
I can deduct that that
To define relation, It can be performed inside of each Model like this
class Shop extends Model {
public function products() {
return this->hasMany('App\Models\Product', 'shop_id');
}
public function user() {
return this->belongsTo('App\Models\Product', 'shop_owner_id');
}
}
class Product extends Model {
public function shop() {
return this->belongsTo('App\Models\Shop', 'shop_id');
}
}
class User extends Model {
public function shop() {
return this->hasMany('App\Models\Shop', 'shop_owner_id');
// or if user can have a single shop
return this->hasOne('App\Models\Shop', 'shop_owner_id');
}
}
Upvotes: 1