本节将学习EloquentRelations。表之间的关系有很多种,比如:一对一:文章和作者,一对多:文章和评论,多对多:标签和文章一对多关系文章和comments一对多关系,主要理解两点:如何实现一对多关系,实现一对多关系后能给开发带来哪些方便先createcomments相关:$phpartisanmake:modelComment-mc同样,将生成的CommentController设为复数,以遵循之前的约定。编辑迁移文件:/database/migrations/2017_04_15_062905_create_comments_table.phppublicfunctionup(){Schema::create('comments',function(Blueprint$table){$table->increments('id');$table->unsignedInteger('post_id');$table->string('body');$table->timestamps();$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');});}我们给comments表添加了post_id外键,同时定义了onDelete级联约束,可以让关联的子表在父表删除时自动删除(文章)被删除(评论)。最后执行迁移:$phpartisanmigrate接下来我们可以定义文章和评论的一对多关系:/app/Post.phppublicfunctioncomments(){return$this->hasMany(\App\Comment::class);}在comments方法中,我们没有指定对应的外键。这是因为我们在定义迁移时严格按照约定(posts_id),所以Laravel会自动找到对应的外键。::class方法也可以写成:return$this->hasMany('\App\Comment');一对多关系的作用定义好文章和评论的一对多关系后,我们就可以轻松的进行相关操作了,下面先来练习一下:$phpartisantinker为了操作方便,我们先让批处理评论内容body字段赋值:/app/Comment.phpprotected$fillable=['body'];首先直接按照文章创建评论:>>$post=\App\Post::first()>>>$post->comments()->create(['body'=>'Comment1'])>>>$post->comments()->create(['body'=>'comment2'])可以发现我们可以直接根据文章实例创建对应的评论,不需要确定评论的post_id字段。创建后,我们可以很方便的获取文章的评论:>>>$post->comments;我们传入comments属性而不是方法,Laravel会返回文章对应的评论集合,比如我们可以将其转换成其他格式:>>>$post->comments->toJson()当然,你也可以使用comments()方法返回Eloquent模型以进行进一步的操作:>>>$post->comments()->get()->toArray()>>>$post->comments()->pluck('body')同理,如果我们要根据评论操作相关文章,需要定义评论和文章的多对一关系:/app/Comment.phppublicfunctionpost(){return$this->belongsTo(\App\Post::class);}重启tinker:>>>$comment=\App\Comment::first()>>>$comment->post;>>>$comment->post->标题;评论展示与创建展示评论展示评论比较简单,直接使用`Bootstrap卡片模板即可:/resources/views/posts/show.blade。php
{{$post->body}}