如何在带有关系表的帖子中显示评论的用户名

时间:2019-11-08 16:59:30

标签: laravel

spread operator

{{ \App\User::where('id', $comment->user_id)->value('name') }}

如果我使用上面的代码

姓名用户在所有帖子中显示

我的模特

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Komen extends Model
{
    protected $table='komentar_post';


}

我的控制器

public function index()
{
    $post=Post::all();
    $comment=Komen::all();
    $user=User::all();

    // dd($id);
    return view('home',compact('post','comment','user'));
}

我的观点

@foreach($comments as $cm)
                {{ \App\User::where('id', $cm->user_id)->value('name') }}
                @endforeach

我必须使用什么corect查询

1 个答案:

答案 0 :(得分:1)

您需要在Komen模型中创建关系。就像这样:

class Komen extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }
}

然后,您可以在获取KomenEager Load建立这种关系。

PostsController.php

public function show(Post $post)
{
    $comments = $post->comments()->with('user')->paginate();

    return view('posts.show', compact('comments'));
}

然后,您可以在显示每个评论时访问user数据:

posts / show.blade.php

@foreach($comments as $comment)
    {{ $comment->user->name }}
@endforeach


{!! $comments->links() !!}

更新

好吧,如果您需要在显示所有帖子时显示评论,则首先需要设置relationship

Post.php

class Post extends Model
{
    public function comments()
    {
        return $this->hasMany(Komen::class, 'post_id');
    }
}

Komen.php

class Komen extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }
}

PostsController.php

public function index()
{
    $posts = Post::with('comments.user')->paginate();

    return view('home', compact('posts'));
}

home.blade.php

@foreach($posts as $post)
    @foreach($post->comments as $comment)
        {{ $comment->user->name }}
    @endforeach
@endforeach

{!! $posts->links() !!}