首页 > 解决方案 > laravel 获取关系数据作为带有分页的单独记录

问题描述

Post 和 Comment 是模型。Post 与 Comment 有很多关系。

如果 post1 有一条评论 (c1),我想将它们作为两条记录获取,一条用于父模型,一条用于关系记录,因此它会显示类似这样的内容。

post_id comment_id  name    owner_name  comment
1       null        p1      owner1      null    //from parent model
1       1           p1      owner1      c1      //from relationship
posts
====

post_id     name    owner_name
1           p1      owner1
2           p2      owner2
3           p3      owner3
4           p4      owner4


comments
========

comment_id  comment     post_id
1           c1          1   
2           c2          1
3           c3          2


Expected results
================
post_id comment_id  name    owner_name  comment
1       null        p1      owner1      null
1       1           p1      owner1      c1
1       2           p1      owner1      c2
2       null        p2      owner2      null
2       3           p2      owner2      c3
3       null        p3      owner3      null
4       null        p4      owner4      null

标签: mysqllaraveleloquent

解决方案


推荐阅读