php - List all users and their recipes
问题描述
I'm writing a custom database query in Laravel for my cocktail app. The goal is to retrieve the following structure:
- User 1
- Recipe 1
- Recipe 4
- User 2
- Recipe 2
- Recipe 3
etc...
My code (see below) currently returns 3 objects, all containing a single recipe but all from 2 users. Is it even possible to build the desired structure (see above), retrieving a user and having his/her recipes stored in a array/object called recipes?
$recipes = DB::table('users')
->join('recipes', 'users.id', '=', 'recipes.user_id')
->select(
'recipes.id as recipe_id',
'recipes.name as recipe_name',
'recipes.short as short',
'users.name as user_name'
)
->get();
解决方案
While in Laravel, use Eloquent.
In your User model add relationship to recipes:
public function recipes()
{
return $this->hasMany('App\Recipe');
}
To call it:
$recepies = App\User::find(1)->recipes;
推荐阅读
- flutter - BitmapDescriptor.fromBytes 在 iOS 上不起作用,但在 Android 上运行良好
- android - 比较不同的 adb 日志
- c - 在 C 中计算破折号以退出 While 循环
- react-native - React Native 垂直粘性滑动标签栏/面板
- javascript - 通过“require”功能将菜单导入浏览器窗口
- firebase - Flutter App 卡在启动画面,没有移动到登录页面或主页
- python - 分类数据计数
- javascript - 尝试在 Angular 的新选项卡中打开网站但无法正常工作
- sql - 如何删除数据库中5分钟内取消的订单记录?
- javascript - 使用反应链接时如何防止外部网址附加到本地主机网址?