获取数据Laravel雄辩模型嵌套JSON阵列关系
我使用laravel使得社交网络,我想,以示“‘后’”在单个阵列中的意见‘comment_by’用户信息与嵌套关系获取数据Laravel雄辩模型嵌套JSON阵列关系
这里是我的阶级和数据库结构
表名和场
成员
ID => primary key,
name,
email
帖子
ID => primary key,
postText
fromUserId => foreign key (Members-id)
评论
commentText ,
onPostId = > foreign key (Post-id)
fromUserId = > foreign key (Members-id)
雄辩模型
1.Member.php
class Member extends Model
{
//
}
2.post.php
class post extends Model
{
//
public $timestamps = true;
function getUserDetails()
{
return $this->belongsTo('App\Member', 'fromUserId', 'id');
}
function getCommentDetails()
{
return $this->hasMany('App\comment', 'onPostId', 'id');
}
}
3.comment.php
呼叫用于获取阵列
$posts=post::with('getUserDetails','getCommentDetails')->get();
*预期输出
{
"id":1,
"postType":1,
"postText":"my name is parth",
"url":null,
"likesCount":0,
"unlikesCount":0,
"shareCount":0,
"commentsCount":0,
"thumbUrl":null,
"accessMode":1,
"fromUserId":1,
"isAdult":1,
"created_at":null,
"updated_at":null,
"get_user_details":{
"id":1,
"name":"parth",
"email":"[email protected]",
"password":"parth123456",
"remember_token":"e1b28a30ab467c52924df64034c386d4",
"created_at":null,
"updated_at":null
},
"get_comment_details":[
{
"id":1,
"commentsText":"dccd",
"onPostId":1,
"fromUserId":1,
"created_at":"2017-05-25 16:44:51",
"updated_at":null
"commented_by":{
"id":1,
"name":"parth",
"email":"[email protected]",
"password":"parth123456",
"remember_token":"e1b28a30ab467c52924df64034c386d4",
"created_at":null,
"updated_at":null
},
},
{
"id":3,
"commentsText":"second comment",
"onPostId":1,
"fromUserId":1,
"created_at":"2017-05-26 09:40:51",
"updated_at":null
"commented_by":{
"id":1,
"name":"parth",
"email":"[email protected]",
"password":"parth123456",
"remember_token":"e1b28a30ab467c52924df64034c386d4",
"created_at":null,
"updated_at":null
},
},
{
"id":4,
"commentsText":"second comment",
"onPostId":1,
"fromUserId":1,
"created_at":"2017-05-26 09:41:16",
"updated_at":null
"commented_by":{
"id":1,
"name":"parth",
"email":"[email protected]",
"password":"parth123456",
"remember_token":"e1b28a30ab467c52924df64034c386d4",
"created_at":null,
"updated_at":null
},
},
{
"id":5,
"commentsText":"third one",
"onPostId":1,
"fromUserId":1,
"created_at":"2017-05-26 09:41:43",
"updated_at":null
"commented_by":{
"id":1,
"name":"parth",
"email":"[email protected]",
"password":"parth123456",
"remember_token":"e1b28a30ab467c52924df64034c386d4",
"created_at":null,
"updated_at":null
},
}
]
}
基于您的评论,只是commentedBy
关系添加到您的Member
模型和贪婪加载它。
在评论模型。
public function commentedBy()
{
return $this->belongsTo('App\Member', 'fromUserId', 'id');
}
然后急切地加载这样的关系。
$posts = post::with('getUserDetails','getCommentDetails.commentedBy')->get();
但我怎么会在这个$ posts = post :: with('getUserDetails','getCommentDetails') - > get(); –
@ParthBhatti更新了我的答案,以及如何急于加载。 – Sandeesh
很棒的工作!这样可行 –
那么究竟是什么问题? – Sandeesh
如何在评论数组中获得“评论_” –
添加了我的答案。这应该做你需要的。 – Sandeesh