Nitish
Nitish

Reputation: 2763

Laravel hasMany relationship

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 ) ?

Upvotes: 0

Views: 78

Answers (1)

Mina Abadir
Mina Abadir

Reputation: 2981

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);

Upvotes: 1

Related Questions