0

I have three tables, stores, store_categories and product_categories. Structure of each table is below

stores

id  name
1   Mystore

store_categories

id   store_id   product_category_id
1       1            1
2       1            2

product_categories

id   name
1    Grocery
2    Vegetable

In my Store model, I write the relation

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

So to get all data of a store, I write i StoresController

$res = Store::with('store_categories')->get(); dump($res);

But the dump shows store_id and product_category_id in relations. How can I display their names( ie store name, product category name etc ) ?

3
  • Did you add the relationships to models? Commented Dec 8, 2015 at 16:10
  • I my Store model , I added this funtion public function store_categories(){ return $this->hasMany('App\StoreCategory'); } Commented Dec 8, 2015 at 16:13
  • Why do not you add ProductCateogry relationship and use store_categories as pivot table? Commented Dec 8, 2015 at 16:18

1 Answer 1

1

You need to add Many to Many relationship as follows:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Store extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function categories()
    {
        return $this->belongsToMany('App\ProductCategory','store_categories','store_id','product_category_id');
    }
}

Then you can perform the following:

$res = Store::with('categories')->get(); dump($res);
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.