简体   繁体   English

从laravel中的数据库获取所有帖子及其评论

[英]get all posts with their comments from database in laravel

I've got a system in which there are users who create posts and they can comment on posts as well. 我有一个系统,其中有users创建帖子,他们也可以评论posts

Here are migrations: 以下是迁移:

users table users

public function up()
{
    Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('gender')->default('Male');
    $table->string('email')->unique();
    $table->string('city')->default('Peshawar');
    $table->string('avatar')->default('user.png');
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});
}

posts table posts

    public function up()
{
    Schema::create('posts', function (Blueprint $table) {


        $table->bigIncrements('p_id');
        $table->text('description');
        $table->integer('user_id');   // this should be user id nothing else
        $table->timestamps();

    });
}

comments table comments

    public function up()
{
    Schema::create('comments', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('user_id'); // who has done comment
        $table->integer('post_id');  // on which post comment has been done
        $table->text('body');
        $table->timestamps();
    });
}

Models 楷模

User Model User模型

class User extends Authenticatable{
use Notifiable;

// custom function used for relationshisp
// user can have many posts

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

// user can have many comments as well

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

} }

Post Model Post模型

class Post extends Model{
   // posts belongs to one user
   public function user(){
    return $this->belongsTo('App\User');
  }


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

 }

Comment Model Comment模型

class Comment extends Model

{ {

// doing this we could insert data into comment table
protected $fillable =['user_id','post_id','body'];
// we need two(2) relations here
// relation of comment with post

// relation of comment with user

// 1. comment belongs to one post // 1.评论属于一个帖子

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

// 2. comment belongs to a user as well // 2.评论也属于用户

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

} }

route

Route::get('/home', 'HomeController@index')->name('home');

Here is the index method in HomeController 这是HomeControllerindex方法

public function index(){
    $posts = Post::with('comments')->get();
    // $comments = Comment::all();

    return view('home')->with( array('posts'=>$posts ) );
}

Problem 问题

So when I visit /home I want to get all posts with their comments . 因此,当我访问/home我希望获得所有帖子的评论

As you can see I've retrieved posts with their comment like this: 正如您所看到的,我已经使用他们的comment检索posts ,如下所示:

$posts = Post::with('comments')->get();

And then I'm passing it to home.blade.php . 然后我将它传递给home.blade.php Here is what I'm doing at home.blade.php to achieve this task. 以下是我在home.blade.php上所做的home.blade.php来完成这项任务。

View /home.blade.php 查看 /home.blade.php

@foreach($posts as $post)

     <h4 class="media-heading">{{$post->user->name}}</h4>
     <small>{{$post->created_at}}</small>

     <p>{{$post->description}}</p>

     <!-- trying to retrieve comments with each post -->

             @if (count($post->comments))
                  @foreach($post->commnents as $comment)
                      <small>$comment->body</small>
                   @endforeach
             @else 
                  No comments Found
             @endif 




 @endforeach

It gives me this error 它给了我这个错误

Undefined variable: post (View: F:\\application\\resources\\views\\home.blade.php) 未定义的变量:post(查看:F:\\ application \\ resources \\ views \\ home.blade.php)

Keeping in mind those models and their relationships with each other, am I doing it in the wrong way to retrieve comments for each post? 记住这些models及其relationships ,我是否以错误的方式为每个帖子检索评论? If so, how can I get all the posts with their comments and when there are no comments it should say no comments found . 如果是这样,我怎么能得到他们的comments所有的posts ,当没有comments它应该说no comments found

Here is what the result return by dd($posts) dd($posts) returning this , have a look at the comments field, that is empty. 以下是dd($posts) dd($ posts)返回结果的结果,看一下注释字段,即为空。

The network tab is showing the following network选项卡显示以下内容 这个 Please help, Thanks to everyone. 请帮忙,谢谢大家。

its probably because of this.. 它可能是因为这个..

public function up()
{
    Schema::create('posts', function (Blueprint $table) {


        $table->bigIncrements('p_id'); <---
        $table->text('description');
        $table->integer('user_id');   // this should be user id nothing else
        $table->timestamps();

    });
}

any reason why you are using p_id instead of id? 您使用p_id而不是id的任何原因? relations work so that id of post is matched to the post_id in the comments table.. if you using this u have to specify this custom key when you are creating the relationship.. 关系工作,以便post的id匹配到comments表中的post_id ..如果你使用这个你必须在创建关系时指定这个自定义键。

check out https://laravel.com/docs/5.8/eloquent-relationships#defining-relationships 看看https://laravel.com/docs/5.8/eloquent-relationships#defining-relationships

Try passing your post custom key as third argument to the relation: 尝试将您的帖子自定义键作为第三个参数传递给关系:

Comment Model 评论模型

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

Maybe a better option will be, change the key of the table posts to 'id' to agree with the conventions of Laravel. 也许更好的选择是,将表格的关键字改为'id'以符合Laravel的惯例。 Create a new migration and run it. 创建一个新的迁移并运行它。

Schema::table('posts', function (Blueprint $table) {
    $table->renameColumn('p_id', 'id');
});

Another option would be, creating the foreign key constraints, to force referential integrity at the database level: 另一种选择是创建外键约束,以强制在数据库级别引用完整性:

posts table 帖子

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->bigIncrements('p_id');
        $table->text('description');
        $table->integer('user_id')->unsigned();
        $table->timestamps();

        $table->foreign('user_id')->references('id')->on('users');
    });
}

comments table 评论

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

        $table->foreign('user_id')->references('id')->on('users');
        $table->foreign('post_id')->references('p_id')->on('posts');
    });
}

You will have to rollback and re-run the migrations (you will lose the data saved in DB). 您必须回滚并重新运行迁移(您将丢失保存在DB中的数据)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM