2015-12-08 8 views
0

У меня есть три стола, stores, store_categories и product_categories. Структура каждой таблицы нижеLaravel hasMany relationship

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 

В моей Store модели, я пишу соотношение

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

Таким образом, чтобы получить все данные в магазине, я пишу я StoresController

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

Но дамп показывает store_id и product_category_id в отношениях. Как я могу отображать их имена (например, имя магазина, название категории продукта и т. Д.)?

+0

Добавили ли вы отношение к моделям? –

+0

Я моя модель магазина, я добавил эту функцию funtion public function store_categories() { return $ this-> hasMany ('App \ StoreCategory'); } – Nitish

+0

Почему вы не добавляете отношения ProductCateogry и используете store_categories как сводную таблицу? –

ответ

1

Вам нужно добавить многие ко многим следующим образом:

<?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'); 
    } 
} 

Затем вы можете выполнить следующие действия:

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