2015-04-07 205 views
0

我试图从数据库加载所有商店,商店地址和城市细节。Laravel雄辩多重连接

  • STORE_ID
  • 描述

store_address

  • STORE_ID
  • 街道
  • 拉链
  • city_id

城市

  • city_id

我设法ŧ o加载所有商店的地址,但我遇到了按城市ID加载城市名称的问题。

这是我目前得到:

{ 
    "store_id":1, 
    "name":"Store Name", 
    "description":"Store description", 
    "created_at":"-0001-11-30 00:00:00", 
    "updated_at":"-0001-11-30 00:00:00", 
    "address":{ 
     "store_id":1, 
     "street":"Street name", 
     "zip":00000, 
     "city_id":1 
    } 
} 

我的代码:

$stores = Store::with('address')->get(); 

class Store extends Eloquent 
{ 

    protected $table = 'stores'; 
    protected $primaryKey = 'store_id'; 

    public function address(){ 
     return $this->hasOne('StoreAddress', 'store_id'); 
    } 
} 

class StoreAddress extends Eloquent 
{ 

    protected $table = 'store_address'; 
    protected $primaryKey = 'store_id'; 

} 

所以我只需要通过city_id从城市表中获取城市的名字,我找不到实例这正是我想要做的。

谢谢。

回答

4

您应该创建belongsTo城市关系到StoreAddress模型。

你需要的东西是这样的:

class StoreAddress extends Eloquent 
{ 

    protected $table = 'store_address'; 
    protected $primaryKey = 'store_id'; 

    public function city() 
    { 
     return $this->belongsTo('City', 'city_id'); 
    } 

} 

Ofcourse,你需要为城市创建一个模型(如果你还没有这么做过)。

+0

谢谢,我已经做了类似的事情,但是我花了一段时间才明白如何在查询中调用city()来获取商店。 – plexcell