2017-04-07 95 views
0

我想用laravel創建一個API,我有一個商店,評論,用戶,食物和shop_food表。我希望api能夠展示商店清單,每個商店都有店鋪信息,5種食品,商店評論和給予評論的用戶。創建json api laravel belongsstomany關係

<?php 

namespace App; 

use App; 

use Illuminate\Database\Eloquent\Model; 

class Shop extends Model 

{ 
    /** 
    * The table associated with the model. 
    * 
    * @var string 
    */ 
    protected $table = 'shops'; 

/** 
* The attributes that are mass assignable. 
* 
* @var array 
*/ 

protected $fillable = ['name','description','address','district','city','country','lat','long','speciality']; 



/** 
* Get the shop associated with the location. 
*/ 
public function comments() 
{ 
    return $this->hasMany('App\Comment'); 
} 

/** 
* Get the shop associated with shops. 
*/ 
public function foods() 
{ 
    return $this->belongsToMany('Food', 'shop_food', 
     'shop_id', 'food_id'); 
} 



} 

我的店控制器

<?php 

namespace App\Http\Controllers; 

use App\Shop; 
use App\Comment; 
use Illuminate\Http\Request; 

class ShopController extends Controller 
{ 
    /** 
    * Display a listing of the resource. 
    * 
    * @return \Illuminate\Http\Response 
    */ 
    public function index() 
    { 
     $shops = Shop::with('comments.user')->get(); 
     return response(['shops' => $shops->toArray(), 'error'=>'false'], 200); 
    } 

什麼我需要做的,請幫助。現在就算是錯誤的我只能顯示商城 - >評論 - >用戶,但我需要添加食品的API

enter image description here

回答

1

如果商店和食品之間的關係是可用的方法..你可以做這樣的事情:

$shops = Shop::with('comments.user', 'foods')->get(); 

這樣,你得到的多重關係,當你$商城 - >指定者(),它會顯示你的API中,對吧?