Laravel Eloquent-将数据透视表的ID用作另一个表中的外键 [英] Laravel Eloquent - Using pivot table's id as a foreign key in another table
问题描述
我需要将数据透视表的ID用作另一个表中的外键.
I need to use pivot table's id as a foreign key in another table.
例如,我有以下表格:
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条目,我在路由表中都有很多条目.
so when user says I am going to that place, I have a new entry in place_user table and start to log the route he takes to get there. So for each place_user entry i have many entries in routes table.
用雄辩的方式建立这种关系的正确方法是什么?我应该为数据透视表创建模型吗?
what is the correct way of doing this kind of relationship using eloquent? Should I create a model for the pivot table?
我已经尝试通过以下解决方案来解决我的问题,但是没有运气: https://github.com. com/laravel/framework/issues/2093#issuecomment-39154456 并在其中发表评论 https: //github.com/laravel/framework/issues/2093#issuecomment-58187802
I have tried to solve my problem by the following solution but no luck: https://github.com/laravel/framework/issues/2093#issuecomment-39154456 and posted a comment there https://github.com/laravel/framework/issues/2093#issuecomment-58187802
任何建议将不胜感激.
推荐答案
经过大量搜索并尝试了不同的解决方案后,我想到了以下解决方案:
After lots of searching and trying different solutions I came up with the following solution:
用户模型:
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中包含的路由类出现问题.
I have Changed name route to footprint to avoid problems with route class included in laravel.
足迹模型:
class Footprint extends \Eloquent {
public function place_user()
{
return $this->belongsTo('PlaceUser');
}
}
最后,我得到了可以进行如下查询的结构:
In the end I get structure where I can make different queries like:
// 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
希望这会有所帮助
这篇关于Laravel Eloquent-将数据透视表的ID用作另一个表中的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!