【发布时间】:2020-07-08 04:07:47
【问题描述】:
我使用的是 laravel 5.7。
我有一个父类“用户”,它可以有很多孩子“cmets”。 我正在尝试根据 cmets 的字符串长度对集合进行排序,如果用户有任何短字符串,则无论他的其他字符串有多长,用户都会出现在集合的早期。
目前我有这段代码,当用户只有一条评论时,它可以正常工作。但是当他们有多个字符串时,它会选择每个用户可用的最长字符串(或者它可能正在计算用户的总字符串长度?)进行排序,而不是最短的字符串
$collection = User::with('comments')->get();
$comment_length = 'comments.questions';
$collection = $collection->sortBy(function($comment_length) { return strlen($comment_length );});
如果我有的话
user1->comment1 = "srt"
user1->comment2 = "superduperveryverylong"
user2->comment1 = "short"
user3->comment1 = "longer1"
user3->comment2 = "longer2"
user3->comment3 = "longer3"
我希望订单为 [1,2,3] 但得到 [2,3,1]。 cmets个数无关(>0时)
任何想法如何为这种情况编写排序函数?
提前致谢!
【问题讨论】: