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,
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