【问题标题】:Laravel eloquent get details from related tableLaravel eloquent 从相关表中获取详细信息
【发布时间】:2020-03-06 13:47:36
【问题描述】:

如果我有两个相关的表,我不明白如何将信息返回给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 包含 users 主键女巫是整数。如何显示用户名?这有点像内部连接,但有可能以雄辩的方式做到这一点吗?还是我完全误解了Model 中的那些公共功能?

【问题讨论】:

    标签: php laravel symfony eloquent


    【解决方案1】:

    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 中阅读有关一对多关系的逆向的更多信息。

    【讨论】:

    • 我有错误:找不到类 'App\User'。我不懂女巫模型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 2022-08-19
    • 2020-11-22
    相关资源
    最近更新 更多