我试图在议程中创建一个''要放在我用Yii2创建的应用程序的索引页面上的项目。
使用下面的功能,我将检索数据库中即将发布的下一个项目'并根据旅行等级和日期显示。我正在使用NOW()表达式。
然而,这意味着下一个即将到来的项目将会显示,直到它到达NOW()日期,因此它在当天不再显示。理想情况下,我应该显示即将到来的项目,直到时间超过$ this->时间或仅在NOW()之后的第二天显示该项目。
任何有关我如何实现这一目标的提示?
public function searchANext($params)
{
$query = Trip::find();
$time = new Expression('NOW()');
$query->where(['class' => Trip::CLASS_A])
->andWhere(['>=', 'date', $time])
->limit(1);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => ['defaultOrder' => ['date' => SORT_ASC]],
'pagination' => false
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
return $dataProvider;
}
答案 0 :(得分:3)
我不知道为什么当你只想获得一条记录时你返回一个ActiveDataProvider
,我认为这种情况是不必要的。
此外,您正在加载$params
并在创建查询后验证模型,因此如果$params
无效,您仍会收到错误并最终返回$dataProvider
否无论加载和验证方法返回什么。
我建议您对代码进行一些更改:
public function searchANext($params)
{
// Try to load $params and validate the model first and return false
// instead of returning the result of the search.
if(!($this->load($params) && $this->validate())) {
return false;
}
// Let's get the currend DateTime. You might need to change this
// depending on the format of the 'date' field from 'Trip'
$now = date('Y-m-d H:i:s');
// Instead of creating an ActiveDataProvider, you can just get the one
// record directly and return it.
$model = Trip::find()
->where(['class' => Trip::CLASS_A])
->andWhere(['>=', 'date', $now])
->orderBy('date ASC')
->one();
return $model;
}