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

时间:2019-06-16 06:56:50

标签: php laravel

我有一个系统,其中有users个帖子创建者,他们也可以对posts进行评论。

以下是迁移:

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

    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

    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();
    });
}

模型

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模型

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模型

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.评论属于一篇帖子

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

// 2.评论也属于用户

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

}

route

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

这是index中的HomeController方法

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

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

问题

因此,当我访问/home时,我希望获得所有带有其评论的帖子。

如您所见,我已经像这样检索了posts和他们的comment

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

然后将其传递给home.blade.php。 这是我在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

它给了我这个错误

  

未定义的变量:发布(视图:F:\ application \ resources \ views \ home.blade.php)

请紧记那些models和他们的relationships,我是否以错误的方式来获取每个帖子的评论?如果是这样,我该如何将所有posts与他们的comments一起使用,当没有comments时,应该说no comments found

这是dd($posts)返回的结果 dd($posts) returning this,查看注释字段,该字段为空。

network标签显示以下this 请帮助,谢谢大家。

2 个答案:

答案 0 :(得分:2)

可能是因为这个原因。

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();

    });
}

为什么要使用p_id而不是id?关系可以正常工作,以使post的ID与注释表中的post_id匹配。.如果使用此ID,则在创建关系时必须指定此自定义键。

签出https://laravel.com/docs/5.8/eloquent-relationships#defining-relationships

答案 1 :(得分:1)

尝试将您的自定义自定义键作为第三个参数传递给该关系:

评论模型

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

也许更好的选择是,将表帖子的键更改为“ id”以符合Laravel的约定。创建一个新迁移并运行它。

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

另一种选择是创建外键约束,以在数据库级别强制引用完整性:

帖子

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');
    });
}

评论

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');
    });
}

您将必须回滚并重新运行迁移(您将丢失数据库中保存的数据)。