Laravel 多態關聯(morphTo,morphMany)
在網站開發的過程當中,常常會遇到 評論商品,評論文章, 評論店鋪 等等,在處理這樣的需求的時候, 常常會新建一張 評論表, 而後經過 一個 type字段來區分 評論的對象 開發過程以下:php
新建表操做網站
php artisan make:model Models/Comments -m
表字段:this
public function up() { Schema::create('comments', function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->integer('member_id'); $table->string('comment_object_type'); # 評論對象 $table->integer('comment_object_id'); # 評論對象的id $table->text('comment_content'); # 評論內容 $table->tinyInteger('status'); }); }
作數據遷移:code
php artisan migrate
造數據
用戶 ID 爲2和4 的用戶對 商品ID 爲 1,2,3,4的商品進行評論:對象
INSERT INTO `comments`(`member_id`,`comment_object_type`,`comment_object_id`,`status`,`created_at`,`updated_at`) VALUES (2,'App\\Models\\Goods',1,0,'2018-09-07 15:58:04','2018-09-07 15:58:04'), (2,'App\\Models\\Goods',2,0,'2018-09-07 15:58:04','2018-09-07 15:58:04'), (2,'App\\Models\\Goods',3,0,'2018-09-07 15:58:04','2018-09-07 15:58:04'), (2,'App\\Models\\Goods',4,0,'2018-09-07 15:58:04','2018-09-07 15:58:04'), (4,'App\\Models\\Goods',3,0,'2018-09-07 15:58:04','2018-09-07 15:58:04'), (3,'App\\Models\\Goods',4,0,'2018-09-07 15:58:04','2018-09-07 15:58:04')
2.用戶ID 爲2 的用戶 對 店鋪ID 爲 1,4 的 店鋪進行了評論開發
INSERT INTO `comments`(`member_id`,`comment_object_type`,`comment_object_id`,`status`,`created_at`,`updated_at`) VALUES (2,'App\\Models\\Stores',1,0,'2018-09-07 15:58:04','2018-09-07 15:58:04'), (2,'App\\Models\\Stores',4,0,'2018-09-07 15:58:04','2018-09-07 15:58:04'),
查詢
數據造完畢, 接下來要作查詢,查詢一下 商品id爲2的 全部評論, 而且查詢出評論人的信息
普通查詢:rem
public function comment_list(Requset $request, Goods $goods) { # 查詢商品的全部評論 $comments = Comment::where('comment_object_type',Goods::class)->where('comment_object_id',$goods->id)->get(); if($comments) { foreach($comments as $comment) { $comment->member = Member::find('id',$comment->member_id) } } dd($comments) }
普通連表查get
Comment.php 文件
# Comment model 文件修改 # 查找評論的用戶的信息 public function member() { return $this->belongsTo(Member::class, 'comment_member_id'); }
需求的查詢string
public function comment_list(Requset $request, Goods $goods) { # 查詢商品的全部評論 $comments = Comment::where('comment_object_type',Goods::class)->where('comment_object_id',$goods->id)->get(); # 省掉了 循環 在模板遍歷的時候 直接調用 $item->member 查看用戶信息 dd($comments) }
多態查詢it
Comment.php 文件
# Comment model 文件修改 # 評論對象 public function comment_object() { return $this->morphTo(); } # 查找評論的用戶的信息 public function member() { return $this->belongsTo(Member::class, 'comment_member_id'); }
Goods.php 文件
# 商品關聯評論 public function comments() { return $this->morphMany(Comment::class,self::class,'comment_object_type','comment_object_id'); }
需求的查詢
public function comment_list(Requset $request, Goods $goods) { # 查詢商品的全部評論 $comments =$goods->comments()->with('member')->paginate(15); dd($comments) }