php 如何在Laravel中创建用户和帖子之间的关系

pokxtpni  于 9个月前  发布在  PHP
关注(0)|答案(4)|浏览(109)

我有一个博客,并希望包括用户名时,向公众展示。
在创建博客时,我确保在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 }}


但这也不管用...

41ik7eoe

41ik7eoe1#

试试这个:

@foreach($blogs as $blog)
<h1>{{$blog->title}}</h1>
{{$blog->user->first_name}} 

@endforeach

字符串
在你的博客模型上

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

3qpi33ja

3qpi33ja2#

在博客控制器中,变量$blog需要为$blogs.。刀片中还有额外的字符(右括号)。它应该是:

@foreach($blogs as $blog)
    <h1>{{ $blog->title }}</h1>
    Source: {{ $blog->user->first_name }} {{ $blog->user->last_name }}
@endforeach

字符串

博客模型

这个函数取代了旧的“users”函数,因为它只返回一个用户(usersTo是一个单一的关系)。

class Blog extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

用户型号

public function blogs()
{
    return $this->hasMany(Blog::class);
}

控制器功能

因此,您可以通过删除冗余元素来减少控制器代码。

public function index(User $user)
{
   $blogs = Blog::where('user_id', '=', $user->id)->orderBy('created_at','desc')->paginate(6);

   return view('blogs.index', compact('blogs'));
}

omjgkv6w

omjgkv6w3#

你所做的就是所谓的查询生成器

$blogs= DB::table('blogs')->where('user_id', '=', $users->id)->orderBy('id', 'DESC')->paginate(6);

字符串
查询生成器不支持延迟加载,因为延迟加载仅支持Eloquent方法

$blog->users->first_name


对于雄辩的方式,你可以尝试这样做,而不是:

$blogs = Blog::where('user_id', $user->id)->get()
foreach($blogs as $blog){
    dd($blog->user); // you will get the user detail here
}


对于延迟加载,当加载大量数据时会出现性能问题,因此为了防止延迟加载,可以使用

$blogs = Blog::with('user')->where('user_id', $user->id)->get()


有关更多信息,请参阅Eloquent Relationship Documentation
对于查询生成器,链接用户的唯一方法是使用join,具体如下所示

$blogs = DB::table('blogs')
        ->join('users', 'users.id', '=', 'blogs.user_id')
        ->get();

foreach($blogs as $blog){
    dd($blog->first_name) // user first name
}


有关更多信息,请查看查询构建器连接

2w3rbyxf

2w3rbyxf4#

BlogController.php

public function index(){
      $blogs = Blog::with('user')->get();
      return view('blogs.index')->with('blogs',$blogs);
}

字符串

博客.php

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

User.php

public function blogs()
{
    return $this->hasMany('App\Blog');
}

相关问题