Laravel Eloquent - Using pivot table's id as a foreign key in another table

后端 未结 1 1317
伪装坚强ぢ
伪装坚强ぢ 2021-02-02 17:45

I need to use pivot table\'s id as a foreign key in another table.

for example i have following tables:

users: id, username, ...

places: id, placename,          


        
相关标签:
1条回答
  • 2021-02-02 18:23

    After lots of searching and trying different solutions I came up with the following solution:

    User Model:

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

    Place Model:

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

    PlaceUser Model:

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

    I have Changed name route to footprint to avoid problems with route class included in laravel.

    Footprint Model:

    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 
    

    hope this helps

    0 讨论(0)
提交回复
热议问题