本篇文章給大家帶來的內容是關于laravel多態關聯的介紹(附代碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。
laravel 多態關聯(morphTo,morphMany)
在網站開發的過程中,經常會遇到 評論商品,評論文章, 評論店鋪 等等,在處理這樣的需求的時候, 經常會新建一張 評論表, 然后通過 一個 type字段來區分 評論的對象 開發過程如下:
新建表操作
php artisan make:model Models/Comments -m
表字段:
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'); }); }
做數據遷移:
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,'AppModelsGoods',1,0,'2018-09-07 15:58:04','2018-09-07 15:58:04'), (2,'AppModelsGoods',2,0,'2018-09-07 15:58:04','2018-09-07 15:58:04'), (2,'AppModelsGoods',3,0,'2018-09-07 15:58:04','2018-09-07 15:58:04'), (2,'AppModelsGoods',4,0,'2018-09-07 15:58:04','2018-09-07 15:58:04'), (4,'AppModelsGoods',3,0,'2018-09-07 15:58:04','2018-09-07 15:58:04'), (3,'AppModelsGoods',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,'AppModelsStores',1,0,'2018-09-07 15:58:04','2018-09-07 15:58:04'), (2,'AppModelsStores',4,0,'2018-09-07 15:58:04','2018-09-07 15:58:04'),
查詢
數據造完畢, 接下來要做查詢,查詢一下 商品id為2的 所有評論, 并且查詢出評論人的信息
普通查詢:
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) }
普通連表查
Comment.php 文件
# Comment model 文件修改 # 查找評論的用戶的信息 public function member() { return $this->belongsTo(Member::class, 'comment_member_id'); }
需求的查詢
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) }
多態查詢
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) }
本篇文章到這里就已經全部結束了,更多其他精彩內容可以關注PHP中文網的php視頻教程欄目!?
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END