问题
I am trying to find out the best way to define the following relation using Laravel's Eloquent Laravel.
I have a User table and 3 Objects ( Player, Team, League) that the user can add as favorites.
I know I can create three pivot tables with the User Model and each one of the objects but then I will need to run a Union query to list all favorites from user regardless of type.
User
id
Favorite
id
user_id
favorited_id ( player_id or team_id or league id)
favorite_type ( player , team or league)
Player
id
Team
id
League
id
Here is my model.
https://www.dropbox.com/s/6au8giufaejcghc/Screen%20Shot%202014-04-07%20at%209.06.51%20AM.png
回答1:
i'd do it the same with a Favourite
table. laravel covers this with its polymorphic relations.
your tables could look like
class Favourite extends Eloquent {
public function favourable()
{
return $this->morphTo();
}
}
class Team extends Eloquent {
public function favourite()
{
return $this->morphMany('Favourite', 'favourable');
}
}
...
your Favourite table would look like
Favourite
favourable_id: int
favourable_type: string
you'd call it like a normal property on the model like $player->favourable()
.
回答2:
You can either use polymorphism as suggested by user3158900, or my preference would be to use Laravel's Query Builder to perform the Union query.
http://laravel.com/docs/queries#unions
$first = DB::table('users')->whereNull('first_name');
$users = DB::table('users')->whereNull('last_name')->union($first)->get();
来源:https://stackoverflow.com/questions/22913605/laravel-orm-user-can-favorite-multiple-models