0

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.

2
  • 2
    Do you have the relationships set up in your Eloquent model i.e. product -belongsTo-> shop and shop -belongsTo-> user (owner)? Commented Nov 18, 2020 at 8:09
  • 1
    Thanks a million. I am wonder how much stupid am I !. Just this relationship setup solves my problem. Commented Nov 18, 2020 at 8:23

1 Answer 1

1

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');
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.