【问题标题】:use eloquent ORM to get data from database使用 eloquent ORM 从数据库中获取数据
【发布时间】:2014-08-08 09:24:18
【问题描述】:

我有一个时间戳数组,我想将它与表中的时间戳进行比较。这是我在控制器中的代码:

public function create(){

    $from = Input::get('from'); //array of timestamps of current messages displayed
    $conv_id = Input::get('conv_id'); //array of ids

    //get all messages related to the array of ids
    $allMessages = Messages::whereIn('conv_id',$conv_id);

    //get the messages in database which have timestamps greater than the current ones displayed.
    $messages = $allMessages->where('created_at','>',$from);

    return $messages->get()->reverse();
}

这适用于单个时间戳传递。但是,如果传递的是一个时间戳数组,Laravel 无法检测到最新消息。我试过了,

$messages = $allMessages->whereIn('created_at','>',$from);

但它返回一个数组到字符串的转换错误。我怀疑我可能用错了。

所以我重复一遍,我如何获取表中时间戳大于我从Input 类获得的时间戳的所有消息?

我认为这可以使用 PHP 的 explode() 来完成,但我希望我的代码尽可能地保持“Laravel-ish”。如果explode()是不可避免的,请告诉我如何使用它。顺便说一句,改进代码的额外印象分!谢谢!

附:这是dd($from) 的结果:

array (size=2)  0 => string '2014-06-18 06:53:45' (length=19)  1 => string '2014-06-18 14:52:29' (length=19)

【问题讨论】:

  • 如果我误解了你,请原谅我,但在我看来,你希望所有消息的时间戳都比 $from 数组中的最新消息晚。如果确实如此,我会说最佳实践是计算那个时间戳并将其提供给查询 - 或者,理想情况下,只将最新的时间戳发送到表单而不是数组开始。
  • 我已经删除了答案,但是这些日期可以使用asort 之类的函数进行排序,并且可以轻松获得最大值。
  • @WereWolf-TheAlpha 感谢您的努力!欣赏它。 :)

标签: php arrays database laravel-4 eloquent


【解决方案1】:

你需要的正是你所拥有的,但要在数组中找到最新的日期并使用它。

这很容易做到

$from = array('2014-06-18 09:10:32', '2014-06-17 10:52:25'); // Input::get('from');
$conv_id = Input::get('conv_id');

asort($from); // Sort the array of dates in order of earliest date first.

$messages = Messages::whereIn('conv_id', $conv_id)->where('created_at', '>', end($from))->get();

这将返回 created_at 时间戳大于 $from 数组中最新日期的所有消息。

【讨论】:

  • +1,这给了我desc 顺序的日期,但更好。
  • @Joe 是的,当然!当所有时间戳总是按彼此的顺序排列并且我可以只比较最新的一个时,我到底为什么要比较 3 个时间戳?哇,我现在觉得很傻。非常感谢!
  • 很高兴我能帮上忙。作为参考,php.net 上的这个页面对于数组排序等很有用。 php.net//manual/en/array.sorting.php
  • @Joe btw,end() 的反义词是什么?
  • 我相信这些方面的东西会起作用。 $first = array_shift(array_values($myArray)); 或使用 $first = reset($array); 可能是更好的解决方案。见:stackoverflow.com/questions/1921421/…
猜你喜欢
  • 2015-01-28
  • 1970-01-01
  • 2021-04-13
  • 2021-01-19
  • 2018-04-09
  • 2017-07-07
  • 2018-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多