Laravel 5.2 从 eloquent 集合中获取最近的日期
Laravel 5.2 get the closest date from eloquent collection
我有 Eloquent 事件模型,它与多个日期相关,如下所示:
$event->dates // shows Collection of 8 Eloquent date models
之后我需要选择唯一的日期,即最接近当前时间的日期。我知道如何使用原始查询 SQL 或数据库 class 来执行此操作。但是有没有更好的解决办法呢?我不想进入数据库获取数据,我已经有了。
eloquent 模型中的日期格式出奇地是字符串。
您可以像这样使用我们在 laravel mutators 中调用的内容 ->
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Event extends Model
{
public function dates()
{
return $this->hasMany('Date');
}
/**
* Get Dates for the event.
*
* @param string $value
* @return array
*/
public function getDates()
{
$dates = $this->dates()->getQuery()->orderBy('created_at', 'asc')->get();
return $dates;
}
}
希望对您有所帮助。
更新
我想现在你也可以像这样在模型定义中直接这样做 -
return $this->hasMany('Date')->orderBy('created_at', 'asc')
我有 Eloquent 事件模型,它与多个日期相关,如下所示:
$event->dates // shows Collection of 8 Eloquent date models
之后我需要选择唯一的日期,即最接近当前时间的日期。我知道如何使用原始查询 SQL 或数据库 class 来执行此操作。但是有没有更好的解决办法呢?我不想进入数据库获取数据,我已经有了。
eloquent 模型中的日期格式出奇地是字符串。
您可以像这样使用我们在 laravel mutators 中调用的内容 ->
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Event extends Model
{
public function dates()
{
return $this->hasMany('Date');
}
/**
* Get Dates for the event.
*
* @param string $value
* @return array
*/
public function getDates()
{
$dates = $this->dates()->getQuery()->orderBy('created_at', 'asc')->get();
return $dates;
}
}
希望对您有所帮助。
更新
我想现在你也可以像这样在模型定义中直接这样做 -
return $this->hasMany('Date')->orderBy('created_at', 'asc')