我该如何吸引发布该帖子的用户 [英] How can i retreive the user who posted the post
问题描述
我正在通过开发一个小型博客来学习laravel.我已经创建了所有必要的关系.但是我无法获得最初创建该帖子的用户的姓名.
I am learning laravel by developing a small blog. I have created all the necessary relationships. But i am unable to get the name of the user who created the post originally.
我尝试过
$post->user->name;
但这会返回 null
,但是如果我这样做
but this returns null
, however if I do
$post->user->id
它返回创建帖子的用户的ID
it returns the id of the user who created the post
我的帖子模型具有这种关系
My post model has this relationship
# Post.php
public function user()
{
return $this->belongsTo('App\Post');
}
我的用户模型具有这种关系
My user model has this relationship
# User.php
public function posts()
{
return $this->hasMany('App\Post');
}
我想要的结果是,如果我写
the results that i want is that if i write
$post->user->name
它应该显示用户名
现在,通过使用以下语句,我得到了类似的结果:
Right now im getting similar results by using this statement:
{{ \App\User::find($post->user_id)->name }}
推荐答案
修正您的关系定义. Post
模型应指向 User
模型:
Fix your relationship definition. The Post
model should point the User
model:
use App\User; // <----
// ...
public function user()
{
return $this->belongsTo(User::class);
} // ^^^^^^^^^^^
此外,您不应该直接从前端进行查询,而是尝试急于加载背面的关系,然后将对象返回视图:
Also, you shouldn't do queries directly from the frontend, instead, try eager loading the relationship in the back and and then return the object to the view:
public function show(Request $request)
{
$post = Post::with('user')->find(1);
// ^^^^^^^^^^^^
return view('my_view')->with('post', $post);
}
然后在您的视图中,您直接使用该对象:
Then in your view you just use the object directly:
<h1> {{ $post->user->name }} </h1>
这篇关于我该如何吸引发布该帖子的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!