【问题标题】:Laravel get all data form two Models and rank them by timestampLaravel 从两个模型中获取所有数据并按时间戳对它们进行排序
【发布时间】:2014-04-16 19:34:31
【问题描述】:

我正在制作这个 Laravel 项目,其中仪表板由一个“时间线”组成,显示所有消息和通知按它们发生的时间排序(“created_at”)。

所以有消息(id、文本、作者、时间戳)和通知(id、action、actegory、object)每个都有不同的字段。

 $messages=Message::orderBy('created_at','DESC')->get();
 $notifications=Notification::orderBy('created_at','DESC')->get();

但我正在寻找一种通过 created_at 将它们一起订购的方法。比如:

array(
message1
notification1
notifcation2
message2
message3
)

此外,我正在寻找一种方法来检查这些元素中的每一个,无论是通知还是消息。

有人知道我是如何做到这一点的吗?

【问题讨论】:

    标签: php arrays laravel laravel-4


    【解决方案1】:

    我认为你需要这样的东西:

    class MessageNotificationComposite implements IteratorAggregate
    {
        private $_elements;
    
        function __construct(array $elements)
        {
            usort(
                $elements,
                function ($a, $b) {
                    if ($a->created_at > $b->created_at) {
                        return 1;
                    } elseif ($a->created_at < $b->created_at) {
                        return -1;
                    }
                    return 0;
                }
            );
            $this->_elements = $elements;
        }
    
        public function getIterator()
        {
            return new ArrayIterator($this->_elements);
        }
    }
    
    $messages = Message::all();
    $notifications = Notification::all();
    
    $mnArray = new MessageNotificationComposite(array_merge($messages, $notifications));
    
    foreach($mnArray as $item) {
        echo get_class($item);
    }
    

    【讨论】:

    • 看起来不错,你会把这个类放在控制器中还是作为库?
    • 复合类 - 作为一个库,调用 - 无论你需要它。
    • 好的,但是我收到 $messages 和 $notifications 不是数组的错误
    • 我有一个错字 - $notification$notifications
    • 修复后出现错误。也许是因为 JSON 格式?
    猜你喜欢
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 2020-03-23
    • 2019-08-11
    • 2022-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多