Laravel Eloquent - 使用数据透视表的 id 作为另一个表中的外键

2024-01-04

我需要使用数据透视表的 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-39154456并在那里发表了评论https://github.com/laravel/framework/issues/2093#issuecomment-58187802 https://github.com/laravel/framework/issues/2093#issuecomment-58187802

任何建议将不胜感激。


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

用户型号:

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');
    }
}

地点用户型号:

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 

希望这可以帮助

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Laravel Eloquent - 使用数据透视表的 id 作为另一个表中的外键 的相关文章

随机推荐