如何组合来自两个模型的数据并按 cakephp 中的创建日期(时间对象)对它们进行排序?
How combine data from two models and sort them by created date (time object) in cakephp?
消息和文件模型属于对话。
消息和文件都有创建的 DATETIME 字段。
我想select属于特定对话的所有消息和文件,并根据创建日期将它们放入同一个供稿中。
如何?
这是我试过的。
//Get us a conversation with all Files and Messages
$conversations = $this->Users->Conversations->find();
$conversations->contain([
'Files' => function ($q)
{
return $q->order('Files.created ASC');
},
'Messages' => function ($q)
{
return $q->order('Messages.created ASC');
},
'Messages.Users',
]);
$conversations->where(['Conversations.id' => $conversationID]);
//Now we want to sort the files an messages according to created date
$converted = $conversations->toArray();
$allEntities = array_merge($converted[0]['files'],$converted[0]['messages']);
$allEntities = Hash::sort($allEntities,'{n}.created','asc');
对于任何不是时间对象的字段,例如 id,这就像一个魅力。
我已经阅读了这个问题Combining lists of data from Multiple Models and sort them by date created in cakephp
但是由于 cakephp 3 将日期时间转换为时间对象,我无法Hash::sort工作。
一种方法是,如果有可能以某种方式关闭时间对象。多半是给我添麻烦了。
有什么建议吗?
Any suggestions?
Link 您的文件直接到 messages
table 而不是将它们链接到对话。您可以使用消息正文字段(或任何您称之为保存消息的字段)将任何数据序列化到其中(例如,如果您想稍后翻译这些值)或者只是在其中包含一个文本字符串 "Foo send File Bar."
如果您在消息中添加 message_type
字段 table 您可以在该字段中使用字符串来标识消息的类型,例如 system
.
您当前的体系结构使它在数据库和应用程序级别非常复杂,比必要的复杂得多。
消息和文件模型属于对话。 消息和文件都有创建的 DATETIME 字段。
我想select属于特定对话的所有消息和文件,并根据创建日期将它们放入同一个供稿中。
如何?
这是我试过的。
//Get us a conversation with all Files and Messages
$conversations = $this->Users->Conversations->find();
$conversations->contain([
'Files' => function ($q)
{
return $q->order('Files.created ASC');
},
'Messages' => function ($q)
{
return $q->order('Messages.created ASC');
},
'Messages.Users',
]);
$conversations->where(['Conversations.id' => $conversationID]);
//Now we want to sort the files an messages according to created date
$converted = $conversations->toArray();
$allEntities = array_merge($converted[0]['files'],$converted[0]['messages']);
$allEntities = Hash::sort($allEntities,'{n}.created','asc');
对于任何不是时间对象的字段,例如 id,这就像一个魅力。
我已经阅读了这个问题Combining lists of data from Multiple Models and sort them by date created in cakephp
但是由于 cakephp 3 将日期时间转换为时间对象,我无法Hash::sort工作。
一种方法是,如果有可能以某种方式关闭时间对象。多半是给我添麻烦了。
有什么建议吗?
Any suggestions?
Link 您的文件直接到 messages
table 而不是将它们链接到对话。您可以使用消息正文字段(或任何您称之为保存消息的字段)将任何数据序列化到其中(例如,如果您想稍后翻译这些值)或者只是在其中包含一个文本字符串 "Foo send File Bar."
如果您在消息中添加 message_type
字段 table 您可以在该字段中使用字符串来标识消息的类型,例如 system
.
您当前的体系结构使它在数据库和应用程序级别非常复杂,比必要的复杂得多。