我有一个博客,并希望包括用户名时,向公众展示。
在创建博客时,我确保在blogs table
中包含user_id
在我的博客模型中,我有以下内容:
public function users()
{
return $this->belongsTo(User::class);
}
字符串
在我的用户模型中,我有:
public function blogs()
{
return $this->hasMany(Blog::class);
}
型
在我的博客控制器中,我有:
public function index(User $user)
{
$users = User::get();
$blogs= DB::table('blogs')->where('user_id', '=', $users->id)->orderBy('id', 'DESC')->paginate(6);
return view('blogs.index',compact('blogs'));
}
型
那么在我看来:
@foreach($blogs as $blog)
<h1>{{$blog->title}}</h1>
Source:{{$blog->users->first_name}} // This does not work
Source:{{$blog->first_name}} // This does not work either
@endforeach
型
我想我可以这样做来显示这些名字:
{{ $blogs->users->first_name }} {{ $blogs->users->last_name }}
型
但这也不管用...
4条答案
按热度按时间41ik7eoe1#
试试这个:
字符串
在你的博客模型上
型
3qpi33ja2#
在博客控制器中,变量
$blog
需要为$blogs.
。刀片中还有额外的字符(右括号)。它应该是:字符串
博客模型
这个函数取代了旧的“users”函数,因为它只返回一个用户(usersTo是一个单一的关系)。
型
用户型号
型
控制器功能
因此,您可以通过删除冗余元素来减少控制器代码。
型
omjgkv6w3#
你所做的就是所谓的查询生成器
字符串
查询生成器不支持延迟加载,因为延迟加载仅支持Eloquent方法
型
对于雄辩的方式,你可以尝试这样做,而不是:
型
对于延迟加载,当加载大量数据时会出现性能问题,因此为了防止延迟加载,可以使用
型
有关更多信息,请参阅Eloquent Relationship Documentation
对于查询生成器,链接用户的唯一方法是使用join,具体如下所示
型
有关更多信息,请查看查询构建器连接
2w3rbyxf4#
BlogController.php
字符串
博客.php
型
User.php
型