Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 934
Tornike Avatar asked Oct 07 '14 14:10

Tornike


1 Answers

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

like image 161
Tornike Avatar answered Sep 18 '22 12:09

Tornike