[英]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:如果我有两个相关表,我不明白如何将信息返回给
blade
template
:
First table is standard Laravel
'users' table Second table:第一个表是标准的
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');
}
Than I have two Controllers
: User
and Recipe
Recipe
have比我有两个
Controllers
: User
和Recipe
Recipe
有
public function user()
{
return $this->belongsTo(\App\User::class);
}
and User
have和
User
有
public function recipes()
{
return $this->hasMany(\App\Recipe::class);
}
actual output looks like this ( RecipesController
):实际输出看起来像这样(
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.一切看起来都
created_by
但列created_by
包含users
主键女巫是整数。 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
?或者我完全误解了
Model
那些公共功能?
Your user relationship in your Recipe model is missing the foreignKey:您的 Recipe 模型中的用户关系缺少外键:
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 .您可以在docs 中阅读有关一对多关系倒数的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.