Abdus Sattar Bhuiyan
Abdus Sattar Bhuiyan

Reputation: 3074

How to get data of nested Relation in laravel

Let me explain the actual case. I have three tables like:

  1. products table enter image description here

  2. shop table:

    enter image description here

  3. users table: enter image description here

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

Answers (1)

Yves Kipondo
Yves Kipondo

Reputation: 5603

I can deduct that that

  • User has shops and Shop belongs to a user
  • Shop has many products and product belongs to a shop

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

Related Questions