我在使用Laravel创建聊天系统时遇到了困难我创建了这样的表来存储这样的消息
inbox_message
->id (PK)
->message
->sentTo
->belongsTo
->isStarred
->isRead
->isDraft
->group_message_id (FK) in the same table (inbox_messages).
现在,group_message_id将作为FK参考ID(FK和PK都在同一个表中)
为了获取我已经实现hasMany
这样的关系
public function child(){
return $this->hasMany(message::class,'group_message_id','id');
}
现在,我没有在孩子中获取所有信息,而是在孩子中获取[]
数组,并像这样单独获取所有信息。
[
{
"id": 2,
"message": "msg2 by patient6 to doctor 3",
"belongsTo": 6,
"sentTo": 3,
"isStarred": 0,
"isDraft": 0,
"isRead": 1,
"group_message_id": 1,
"created_at": "2017-09-05 03:48:19",
"updated_at": "2017-09-05 06:52:33",
"deleted_at": null,
"child": []
},
{
"id": 4,
"message": "msg4 by patient6 to doctor 3",
"belongsTo": 6,
"sentTo": 3,
"isStarred": 0,
"isDraft": 0,
"isRead": 1,
"group_message_id": 1,
"created_at": "2017-09-05 03:54:35",
"updated_at": "2017-09-05 06:52:33",
"deleted_at": null,
"child": []
}
]
我用来获取结果的查询
$userMsgs = message::with( [
'child' => function ( $query ) {
$query->where( 'isDraft', '!=', 1 );
}
] )->where( 'isDraft', '!=', 1 )
->where( 'sentTo', $authId )
->get();
问题是如果是的话,可以将相同的表格联系起来,那么请告诉我哪里错了?
感谢我非常需要帮助:)
答案 0 :(得分:2)
尝试使用自我关系
class message extends Eloquent {
function child(){
return $this->hasMany('message', 'group_message_id');
}
}
希望这会有帮助。