当前位置: 首页 > 后端技术 > PHP

Laravel多态关联(morphTo,morphMany)

时间:2023-03-29 19:26:30 PHP

在网站开发过程中,Laravel多态关联(morphTo、morphMany)经常会遇到商品评论、文章评论、店铺评论等,在处理此类需求时,往往会新建一个评论表,然后通过一个type字段用于区分comments的对象开发过程如下:新建表操作phpartisanmake:modelModels/Comments-mtablefield:publicfunctionup(){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');});}做数据迁移:phpartisanmigrate创建数据用户ID作为用户2和4对产品ID为1、2、3和4的产品进行评论:INSERTINTO`comments`(`member_id`,`comment_object_type`,`comment_object_id`,`status`,`created_at`,`updated_at`)VALUES(2,'App\\Models\\Goods',1,0,'2018-09-0715:58:04','2018-09-0715:58:04'),(2,'App\\Models\\Goods',2,0,'2018-09-0715:58:04','2018-09-0715:58:04'),(2,'App\\Models\\Goods',3,0,'2018-09-0715:58:04','2018-09-0715:58:04'),(2,'App\\Models\\Goods',4,0,'2018-09-0715:58:04','2018-09-0715:58:04'),(4,'App\\Models\\Goods',3,0,'2018-09-0715:58:04','2018-09-0715:58:04'),(3,'App\\Models\\Goods',4,0,'2018-09-0715:58:04','2018-09-0715:58:04')2.用户ID为2的用户评论了店铺ID为1,4的店铺INSERTINTO`comments`(`member_id`,`comment_object_type`,`comment_object_id`,`status`,`created_at`,`updated_at`)VALUES(2,'App\\Models\\Stores',1,0,'2018-09-0715:58:04','2018-09-0715:58:04'),(2,'App\\Models\\Stores',4,0,'2018-09-0715:58:04','2018-09-0715:58:04'),查询数据创建完成,接下来就是查询,查询商品id为2的所有评论,并查询评论者的信息普通查询:publicfunctioncomment_list(Requset$request,Goods$goods){#查询商品的所有评论$comments=Comment::where('comment_object_type',Goods::class)->where('comment_object_id',$goods->id)->get();if($comments){foreach($commentsas$comment){$comment->member=Member::find('id',$comment->member_id)}}dd($comments)}普通链表查询Comment.php文件#修改评论模型文件#查找评论的用户信息publicfunctionmember(){返回$this->belongsTo(Member::class,'comment_member_id');}需求查询publicfunctioncomment_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文件#修改评论模型文件#评论对象publicfunctioncomment_object(){return$this->变形();}#查找被评论用户的信息publicfunctionmember(){return$this->belongsTo(Member::class,'comment_member_id');}Goods.php文件#商品相关评论publicfunctioncomments(){return$this->morphMany(Comment::class,self::class,'comment_object_type','comment_object_id');}必填查询publicfunctioncomment_list(Requset$request,Goods$goods){#查询商品的所有评论$comments=$goods->comments()->with('member')->paginate(15);dd($评论)}