2014-10-07 96 views
8

我需要使用数据透视表的ID作为另一个表中的外键。Laravel Eloquent - 在其他表中使用数据透视表的ID作为外键

,比如我有以下表格:

users: id, username, ... 

places: id, placename, lat, lng, ... 

place_user: id, user_id, place_id 

routes: place_user_id, lat, lng, inserted_at. 

所以当用户说,我要去那个地方,我在place_user表中的新条目并开始记录他需要到那里的路线。因此,对于每个place_user条目,我在路由表中有许多条目。

使用口才做这种关系的正确方法是什么?我应该为数据透视表创建一个模型吗?

我曾尝试用以下解决方案,但没有运气,以解决我的问题:https://github.com/laravel/framework/issues/2093#issuecomment-39154456和发布的评论有https://github.com/laravel/framework/issues/2093#issuecomment-58187802

任何建议,将不胜感激。

+0

如果我理解正确的话,你想'用户'和'位置'之间的关系,使用'place_user'表。什么是“路线”表? – Jerodev 2014-10-07 14:59:42

+0

我有很多很多关系的用户和地方,以及路线和place_user关系表之间的一对多关系。 – KoKo 2014-10-07 15:05:41

+0

您需要为数据透视表使用额外的模型,其中一个扩展'模型'('Eloquent')而不是'Pivot'。 'Pivot'具有构造函数,将使其无法工作。如果你需要使用'pivot'属性(在关系的上下文中),那么你只需要定制枢轴模型(扩展'Pivot')。 – 2014-10-07 15:51:14

回答

10

经过大量的搜索和尝试不同的解决方案,我想出了以下解决方案:

用户模型:

class User extends \Eloquent { 
    public function places() { 
     return $this->hasMany('PlaceUser')->with('Place'); 
    } 
} 

放置模型:

class Place extends \Eloquent { 
    public function users() { 
     return $this->hasMany('PlaceUser')->with('User'); 
    } 
} 

PlaceUser型号:

class PlaceUser extends \Eloquent { 

    public function user() { 
     return $this->belongsTo('User'); 
    } 

    public function place() { 
     return $this->belongsTo('Place'); 
    } 

    public function footprints() { 
     return $this->hasMany('Footprint'); 
    } 
} 

我已更改脚印的名称路由,以避免与laravel中包含的路由类有关的问题。

足迹模型:

class Footprint extends \Eloquent { 
    public function place_user() 
    { 
     return $this->belongsTo('PlaceUser'); 
    } 
} 

最后我得到的结构,我可以做出不同的查询,如:

// gets all places with corresponding pivot table entries and users table entries  
Place::with('users')->get(); 
// get user with id=1 including corresponding pivot table entries and places table entries 
User::with('places')->find(1); 
// get footprint of the user 
$user->places->get(0)->footprints 

希望这有助于

相关问题