增加评论功能需要创建新的表:
php artisan make:migration create_comments_table --create=comments php artisan make:model Comment
修改迁移文件:
public function up() { Schema::create('comments', function (Blueprint $table) { $table->increments('id'); // 评论段落 $table->text('body'); // user_id 属于哪个用户 $table->integer('user_id')->unsigned(); // discussion_id 属于哪篇文章 $table->integer('discussion_id')->unsigned(); // 声明user_id外键 $table->foreign('user_id') ->references('id') ->on('users') ->onDelete('cascade'); // 声明discussion_id外键 $table->foreign('discussion_id') ->references('id') ->on('discussions') ->onDelete('cascade'); $table->timestamps(); }); }
在模型中声明关系方法,易于调用:
class Comment extends Model { protected $fillable = ['body', 'user_id', 'discussion_id']; // 关联到discussion public function discussion() { return $this->belongsTo(Discussion::class); } // 关联到user public function user() { return $this->belongsTo(User::class); } }
class Discussion extends Model { protected $fillable = ['title', 'body', 'user_id', 'last_user_id']; // 关联到User public function user() { return $this->belongsTo(User::class); } // 关联到comment public function comments() { return $this->hasMany(Comment::class); } }
在user中:
// 关联到comment public function comments() { return $this->hasMany(Comment::class); }
新增加factory方法:
$factory->define(AppComment::class, function ($faker) { $user_ids = AppUser::lists('id')->toArray(); $discussion_ids = AppDiscussion::lists('id')->toArray(); return [ 'body' => $faker->paragraph, 'user_id' => $faker->randomElement($user_ids), 'discussion_id' => $faker->randomElement($discussion_ids), ]; });
在tinker中批量生成:
factory('AppComment',50)->create();
现在,我们可以随意在一篇文章中展示评论,修改show.blade.php:
<div class="container"> <div class="row"> <div class="col-md-9"> <div class="blog-post"> {!! $text !!} </div> <hr /> @foreach($discussion->comments as $comment) <div class="media"> <div class="media-left"> <a href="#"> <img class="media-object img-circle" src="{{ $comment->user->avatar }}" alt="64x64" style=" 64px; height: 64px;"> </a> </div> <div class="media-body"> <h4 class="media-heading">{{ $comment->user->name }}</h4> {{ $comment->body }} </div> </div> @endforeach </div> </div> </div>