问题
I have four tables:
- foods: id, name
- users: id, name
- mealtypes: id, name
- food_user: id, food_id, user_id, mealtype_id
foods and user have a many-to-many relationship mealtype has a one-to-one relationship with food_user
In the end I would like to have an instance of a model with the following properties: food.name, users.name, mealtype.name
normal sql would be:
SELECT f.name, u.name, m.name FROM foods f
INNER JOIN food_user fu ON f.id = fu.food_id
INNER JOIN users u ON fu.id = u.id
INNER JOIN mealtypes m ON fu.mealtype_id = m.id
Thanks for any help!
回答1:
You could do something like this with Eloquent and Query Builder, assuming you have a model named Food:
$foods = Food::join('food_user', 'foods.id', '=', 'food_user.food_id')
->join('users', 'food_user.user_id', '=', 'users.id')
->join('mealtypes', 'food_user. mealtype_id', '=', 'mealtypes.id')
->get();
There's a good documentation about the query builder too: http://www.laravel.com/docs/queries
回答2:
To answer my own question a year later. I actually asked the wrong question. A pivot table is just a many-to-many relationship between two tables. If a table that represents this many-to-many relationship additionally relates to other tables it is not a pivot table. So in my case the table food_user should represent an eloquent entity on its own with the three relationships defined.
Update, generic solution:
I cannot give you my final solution in terms of Eloquent, since I haven't used it in ages (and didn't implement it there), so I do not have the knowledge anymore. In more general terms, one would need to create 4 models:
- Food
- User
- MealType
- Meal (instead of FoodUser, don't like that name)
Now, in the model Meal, you need to define your relations with the other models:
- Meal.food has a many to one relation with Food
- Meal.user has a many to one relation with User
- Meal.mealType has a many to one relation with MealType
- Some other properties such as Meal.calories (int) and Meal.date (DateTime)
来源:https://stackoverflow.com/questions/16552481/how-to-perform-additional-inner-join-on-pivot-table-with-laravel-eloquent