繁体   English   中英

Laravel eloquent 从相关表中获取详细信息

[英]Laravel eloquent get details from related table

如果我有两个相关表,我不明白如何将信息返回给blade template

第一个表是标准的Laravel 'users' 表第二个表:

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');
}

比我有两个ControllersUserRecipe Recipe

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

User

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

实际输出看起来像这样( RecipesController ):

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

一切看起来都created_by但列created_by包含users主键女巫是整数。 如何显示用户名? 这有点像内连接,但有可能以雄辩的方式做到这一点吗? 或者我完全误解了Model那些公共功能?

您的 Recipe 模型中的用户关系缺少外键:

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

然后,您可以在控制器中使用您的食谱预先加载用户:

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

最后,您可以在视图中访问用户:

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

您可以在docs 中阅读有关一对多关系倒数的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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