【问题标题】:Laravel 5: Fetch commentsLaravel 5:获取评论
【发布时间】:2020-01-31 14:51:11
【问题描述】:

我正在构建一个博客评论系统。

我想在 show.blade.php 中显示用户的 cmets。

在我的ResultsController中我执行了

dd($post->cmets);

但我无法从我的数据库中检索任何 cmets。

我在一个帖子中播种了四个 cmets。 并且用户可以回复每一条评论。

迁移表

Schema::create('comments', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('user_id');
        $table->integer('post_id');
        $table->text('body');
        $table->integer('comment_id')->nullable();
        $table->timestamps();
    });

comment.php

public function posts()
{
    return $this->belongsTo(Post::class);
}

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

public function replies()
{
    return $this->hasMany(Comment::class, 'comment_id')->whereNotNull('comment_id');
}

Post.php

 public function comments()
{
    return $this->hasMany(Comment::class)->whereNull('comment_id');
}

用户.php

public function comments()
{
    return $this->hasMany(Comment::class);
}

Mysql

ResultsController.php

 public function show($id,Post $post)
{
    $particular_post= Post::find($id);
    $recommended_posts = Post::latest()
                            ->whereDate('date','>',date('Y-m-d'))
                            ->where('category_id','=',$particular_post->category_id)
                            ->where('id','!=',$particular_post->id)
                            ->limit(7)
                            ->get();

    $posts['particular_post'] = $particular_post;
    $posts['recommended_posts'] = $recommended_posts;

    dd($post->comments);

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

http://127.0.0.1:8000/results/52 这是应该获取 cmets 的 URL。

【问题讨论】:

  • ->whereNull('comment_id') 不应该是->whereNotNull('comment_id')吗?
  • 为什么whereNull?
  • 因为我只想获取第一个 cmets。每条评论都有comment_id,是对一条评论的回复。
  • @kerbholz 我试过了,但没用。
  • return $this->hasMany(Comment::class)->limit(1) 获取单个评论

标签: php sql laravel get comments


【解决方案1】:

方法注入仅在路由映射中的变量和函数的参数具有相同名称时起作用,您也只需接受帖子本身作为参数,您不需要帖子和 id它。

将您的 show 函数更改为:

public function show(Post $post)
{
    $recommended_posts = Post::latest()
                            ->whereDate('date','>',date('Y-m-d'))
                            ->where('category_id','=',$post->category_id)
                            ->where('id','!=',$post->id)
                            ->limit(7)
                            ->get();

    $posts['particular_post'] = $post;
    $posts['recommended_posts'] = $recommended_posts;

    dd($post->comments);

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

然后确保路由映射中的变量与show的参数同名,即:

Route::get('results/{post}', 'ResultsController@show');

【讨论】:

    猜你喜欢
    • 2016-07-06
    • 2020-02-01
    • 2016-03-21
    • 2014-01-23
    • 2017-03-03
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 2018-08-16
    相关资源
    最近更新 更多