how to perform additional inner join on pivot table with laravel eloquent

左心房为你撑大大i 提交于 2020-05-25 08:07:30

问题


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:

  1. Food
  2. User
  3. MealType
  4. Meal (instead of FoodUser, don't like that name)

Now, in the model Meal, you need to define your relations with the other models:

  1. Meal.food has a many to one relation with Food
  2. Meal.user has a many to one relation with User
  3. Meal.mealType has a many to one relation with MealType
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!