2017-04-07 96 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中,对吧?