我如何在单个论坛中显示这么多评论 post

how to i show so many comments in single forum post


这是我的评论 table

Schema::create('comments', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('post_id')->unsigned();
        $table->foreign( 'post_id' )->references( 'id' )->on( 'posts' )->onDelete('cascade');
        $table->string('comments');
        $table->timestamps();
    });
}

这是我的posttable

Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title')->index();
        $table->timestamps();
    });

在我的 post 模型上我给了 hasMany

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

在我的评论模型中,我给了 belongsToo

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

这是我的控制器

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Http\Requests;
use App\comment;
use App\post;
use Crypt;


class PostController extends Controller
{
    public function index() {
        $posts = post::orderBy('created_at', 'desc')->paginate(9);
        return view('post.index', compact('posts'));
    }

public function create(){

    return view('post.create');
}

public function store(Request $request){

    $post = new post;
    $post->title = $request->title;
    $post->save();
    return redirect()->route('rules');
}

public function show($title){

$post = post::where('title', $title)->first();
$comments = post::orderBy('created_at', 'desc')->paginate(10);

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

public function storecomment(request $request){

    $comment = new comment;
    $comment->post_id = Crypt::decrypt(Input::get('post_id'));
    $comment->comments = $request->comments;
    $comment->save();

    return redirect()->route('rules');
}
}

我看到了每个 post 中的所有评论 我在视图中输入的内容显示 post_id

的评论

获得对每个 post

的评论
@foreach($post as $p)
   @foreach($p->comments as $comment)
    {{ $comment->comments }}
   @endforeach
@endforeach

首先,删除

$comments = post::orderBy('created_at', 'desc')->paginate(10);

来自 show() 函数。(不要忘记也从 compact() 中删除 'comments'

现在,将此添加到您的视图文件中:

@foreach($post->comments->orderBy('created_at', 'desc') as $comment)
   {{ $comment->title... }}
@endforeach