-
I think your setup looks right.
-
You might be wanting to 'Eager Load' the person with the ChatMessages? https://laravel.com/docs/5.3/eloquent-relationships#eager-loading
Something like:
Chat::find(1)->chatMessages()->with('person')->getResults();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I am writing a RESTful chatbot, I have three tables, one for a person, one for chat and one for chatMessage.
A chat is comprised of chatMessages A chatMessage belongs to a chat and has a person (who authored the message)
see this gist for my models and migrations...
https://gist.github.com/matgargano/e4790425451aebc8fe105fca525c556d
Assuming the above is correct... if I want to get all of the chat messages from a chat I have an endpoint http://chatservice.dev/api/chat/1 which performs this query:
Chat::find(1)->chatMessages()->getResults(); and returns an array of objects like so:
{
"data": [
{
"id": 1,
"chat_id": 1,
"person_id": 1,
"message": "Ad alias iusto ea ut ipsum rerum.",
"created_at": "2016-12-04 17:35:11",
"updated_at": "2016-12-04 17:35:11"
},
{
"id": 2,
"chat_id": 1,
"person_id": 2,
"message": "Unde odio enim beatae et labore consequuntur.",
"created_at": "2016-12-04 17:36:44",
"updated_at": "2016-12-04 17:36:44"
},
{
"id": 3,
"chat_id": 1,
"person_id": 2,
"message": "Quod dolorum aut ut pariatur hic ducimus vero.",
"created_at": "2016-12-04 17:36:53",
"updated_at": "2016-12-04 17:36:53"
}
],
"code": 200
}
Two questions:
{
"data": [
{
"id": 1,
"chat_id": 1,
"person": {
"id": 1,
"name": "Jane Doe",
},
"message": "Ad alias iusto ea ut ipsum rerum.",
"created_at": "2016-12-04 17:35:11",
"updated_at": "2016-12-04 17:35:11"
},
{
"id": 2,
"chat_id": 1,
"person": {
"id": 2,
"name": "John Doe",
},
"message": "Unde odio enim beatae et labore consequuntur.",
"created_at": "2016-12-04 17:36:44",
"updated_at": "2016-12-04 17:36:44"
},
{
"id": 3,
"chat_id": 1,
"person": {
"id": 2,
"name": "John Doe",
},
"message": "Quod dolorum aut ut pariatur hic ducimus vero.",
"created_at": "2016-12-04 17:36:53",
"updated_at": "2016-12-04 17:36:53"
}
],
"code": 200
}
instead
Thanks for any help at all.
I think your setup looks right.
You might be wanting to 'Eager Load' the person with the ChatMessages? https://laravel.com/docs/5.3/eloquent-relationships#eager-loading
Something like:
Chat::find(1)->chatMessages()->with('person')->getResults();
Please or to participate in this conversation.