简体   繁体   中英

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

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, lat, lng, ...

place_user: id, user_id, place_id

routes: place_user_id, lat, lng, inserted_at.

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?

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

any suggestions will be appreciated.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM