首页 > 解决方案 > 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:

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();

标签: phplaravel-5

解决方案


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;

https://laravel.com/docs/5.6/eloquent-relationships


推荐阅读