在关系()方法中定义自定义排序标准
我有一个模型 A
,它与模型 B
具有类型 HAS_MANY
的关系。
B
的属性是:
id,
user_id,
message,
date,
parent_message_id
我需要模型 B
的元素按日期(降序)排序,但如果 parent_message_id
与null,考虑的日期应该是parent_message_id对应的日期。
是否可以自定义用于排序关系的标准?
I have a model A
that has a relationship of type HAS_MANY
with model B
.
B
's attributes are:
id,
user_id,
message,
date,
parent_message_id
I need elements of model B
to be ordered by date (descending), but in case the parent_message_id
is different from null, the date to be taken into consideration should be the date corresponding to parent_message_id
.
Is it possible to customize the criteria used to order the relation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,我通过以下方式解决了这个问题:模型 A HAS_MANY 模型 B,因此,我将关系方法重新定义为以下内容:
因此,我只比较那些没有父 ID 的消息的日期。缺点是我必须访问每个帖子的“子消息”......但是,找不到其他解决方法。感谢大家的帮助!
Ok, i solved this the following way: model A HAS_MANY model B, therefore, i redefined the relationships method to the following:
Therefore, I only compare the date of those messages with no parent id. The downside is that I have to access each post's "child messages"... but well, couldn't find another workaround. Thanks all for your help!
我认为只能根据同一列对元素进行排序。但是,可能有一个数据库忍者可以帮助您。
在完美的世界中,您可以使用 afterFind() 方法任何级别的任何自定义,不仅可以排序,还可以更改其他值的某些值。也许它不如计划订单快,但这样可以减轻 MySQL 服务器的负载。另外它是自动调用的。干杯
I think it is only possible to sort elements according to the same column. However there might be a database ninja that could help you.
In an perfect world you could use the afterFind() method for any customization at any level, not only sorting, but also changing some values for others. It is not as fast as a plan order, maybe, but this way you release the MySQL server from a little load. Plus it is called automatically. Cheers