简体   繁体   中英

Laravel eloquent get details from related table

I don't understand how to return info back to blade template if I have two related tables:

First table is standard Laravel 'users' table Second table:

Schema::create('recipes', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('code', 10);
    $table->string('description');
    $table->float('size');
    $table->bigInteger('created_by')->unsigned();
    $table->string('status')->default('pending');
    $table->boolean('deleted');
    $table->timestamps();

    $table->foreign('created_by')
        ->references('id')
        ->on('users')
        ->onDelete('cascade');
}

Than I have two Controllers : User and Recipe Recipe have

public function user()
{
    return $this->belongsTo(\App\User::class);
}

and User have

public function recipes()
{
    return $this->hasMany(\App\Recipe::class);
}

actual output looks like this ( RecipesController ):

$recipes = Recipe::latest()->paginate($perPage);
return view('admin.recipes.index', compact('recipes'));

everything looks OK but column created_by contain users primary key witch is integer. How can I display users name? This is something like inner join but is it possible to do that in eloquent? Or I completely misunderstanding those public functions in a Model ?

Your user relationship in your Recipe model is missing the foreignKey:

public function user()
{
    return $this->belongsTo(\App\User::class, 'created_by');
}

You can then eager load the users with your recipes in the controller:

$recipes = Recipe::with('user')->latest()->paginate($perPage);
return view('admin.recipes.index', compact('recipes'));

And finally you can access the user in the view:

@foreach($recipes as $recipe)
    {{ $recipe->user->name }}
@endforeach

You can read more about the inverse of the one-to-many relationship in the docs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM