I have dataprovider to get 9 posts order by create time but my order and limit not worked
$dataProviderlatenew=new ActiveDataProvider([
'query'=>Post::find()->limit(9)->orderBy('create_time DESC'),
'sort' => [
'defaultOrder' => [
'create_time' => SORT_DESC,
],
],
]);
Remember that if pagination is not false the limit is managed automatically and not using the limit you have in query .. so for the order
$dataProviderlatenew=new ActiveDataProvider([
'query'=>Post::find(),
'sort' => [
'defaultOrder' => [ 'create_time' => SORT_DESC, ],
],
]);
otherwise set aproper pagination (so you can use limit(9) ) and don't impose an order in select and a default order in dataProvider (is a non sense)
eg:
$dataProviderlatenew=new ActiveDataProvider([
'query'=>Post::find(),
'pagination' =>['pagesize' =>9],
'sort' => [
'defaultOrder' => [ 'create_time' => SORT_DESC, ],
],
]);
or
$dataProviderlatenew=new ActiveDataProvider([
'query'=>Post::find()->limit(9),
'pagination' =>false,
'sort' => [
'defaultOrder' => [ 'create_time' => SORT_DESC, ],
],
]);
Try This :
$dataProviderlatenew=new ActiveDataProvider([
'query'=>Post::find(),
'pagination'=>['pagesize'=>9],
'sort' => [
'defaultOrder' => [ 'create_time' => SORT_DESC],
],
]);
Refer : http://www.yiiframework.com/doc-2.0/guide-output-data-providers.html
Related
I am using the yii2 framework with the 'queue' extension. This extension may fail, which is saved in the log file, and I would like to view the error in a specific view.
I was able to log errors into a specific .log file, so the real question is, how can I view errors from another log file?
Yii framework use category distinguish log file
configļ¼
return [
'bootstrap' => ['log'],
'timeZone' => 'PRC',
'components' => [
'log' => [
'targets' => [
//default
[
'class' => 'yii\log\DbTarget',
'levels' => ['error', 'warning'],
],
//especially
[
'class' => 'yii\log\DbTarget',
'levels' => ['error'],
'categories' => ['yii\db\*'],//The point
'logFile'=>'log.txt',//you custom file
],
//especially2
[
'class' => 'yii\log\DbTarget',
'levels' => ['error'],
'categories' => ['app\models'],//The point
'logFile'=>'log.txt',//you custom file
],
//especially3
[
'class' => 'yii\log\DbTarget',
'levels' => ['error'],
'categories' => ['abc'],//The point
'logFile'=>'log.txt',//you custom file
],
],
],
],
];
Use it
Yii::trace('db error');
Yii::trace('start calculating average revenue', __METHOD__);
Yii::trace('start calculating average revenue', 'abc');
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
'error' =>
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
'categories' => ['yii\queue\Queue'],
'logFile' => '#runtime/logs/error.log',
//'enabled' => YII_DEBUG,
//'exportInterval' => 1,
],
],
],
I'm a little bit confused. I'm wondering what is the difference between Yii2 ActiveDataProvider and SQLDataProvider? I was looking in the documentation for it, but couldn't get it too.
Could someone explain me when should I use one or another? And what is the difference between it?
Thank you for your time.
SqlDataProvider works with a raw SQL statement which is used to fetch the needed data and ActiveDataProvider can take either a yii\db\Query or yii\db\ActiveQuery object.
SqlDataProvider example:
$provider = new SqlDataProvider([
'sql' => 'SELECT * FROM post WHERE status=:status', //HERE
'params' => [':status' => 1],
'totalCount' => $count,
'pagination' => [
'pageSize' => 10,
],
'sort' => [
'attributes' => [
'title',
'view_count',
'created_at',
],
],
]);
ActiveDataProvider example:
$query = Post::find()->where(['status' => 1]); // ActiveQuery here
$provider = new ActiveDataProvider([
'query' => $query, // and here
'pagination' => [
'pageSize' => 10,
],
'sort' => [
'defaultOrder' => [
'created_at' => SORT_DESC,
'title' => SORT_ASC,
]
],
]);
i want to put a log in app.log ,My config file
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
'file' => [
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
'logFile' => '#root/console/runtime/logs/app.log',
],
]
]
in controller action
public function actionRankCalculation()
{
$allConest = Contest::find()->where('isActive = 1')->all();
Yii::trace('start calculating average revenue');
$response = [];
/** #var Contest $contest */
foreach ($allConest as $contest) {
$videoQuery = Video::find()->where('contest_id = ' . $contest->id);
$videoQuery->andWhere('isActive = 1');
$videoQuery->orderBy([
'global_likes' => SORT_DESC,
'id' => SORT_ASC,
]);
}
But Yii::trace('start calculating average revenue'); not working
You try this.Use categories. For example like below
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error'],
'categories' => ['test1'],
'logFile' => '#app/Test/test1.log',
],
And use below one in controller action
public function actionIndex(){
Yii::error('Test index action', $category = 'test1'); }
Try to set both flushInterval and exportInterval to 1 in console config:
return [
'bootstrap' => ['log'],
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'exportInterval' => 1,
],
],
'flushInterval' => 1,
],
],
];
It makes each log message appearing immediately in logs.
I have the following search function in my BlogPostSearch ActiveRecord:
public function search($params)
{
$query = BlogPost::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'attributes' => [
'publishDate' => [
'asc' => ['(CASE state
WHEN '.static::STATE_ONLINE.' THEN published_at
WHEN '.static::STATE_OFFLINE.' THEN updated_at
END)' => SORT_ASC],
'desc' => ['(CASE state
WHEN '.static::STATE_ONLINE.' THEN published_at
WHEN '.static::STATE_OFFLINE.' THEN updated_at
END)' => SORT_DESC],
'default' => SORT_DESC
],
],
],
]);
return $dataProvider;
}
But part of my soul dies every time I concatenate a parameter into SQL. Is it possible to bind variables in here?
Something like:
...
'asc' => [
'expression'=> [
'(CASE state
WHEN :online THEN published_at
WHEN :offline THEN updated_at
END)' => SORT_ASC
],
'params' => [
'online' => static::STATE_ONLINE,
'offline' => static::STATE_OFFLINE,
],
],
...
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
'access' => [
'class' => AccessControl::className(),
'only' => ['create', 'update', 'delete', 'view', 'index'],
'rules' => [
// allow authenticated users
[
'allow' => true,
'roles' => ['#'],
],
// everything else is denied by default
],
],
[
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['create_time', 'update_time'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['update_time'],
],
],
];
}
Above code is for my controller behavior function. While creating or updating, 'create_time' and 'update_time' fields are not getting updated by current time. Type of those fields are set to datetime. Please need your help.
You have to declare it in the behaviors method of your model.
To use TimestampBehavior, insert the following code to your ActiveRecord class
public function behaviors()
{
return [
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['create_time', 'update_time'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['update_time'],
],
];
}
Try this, it works for me:
use yii\db\Expression;
...
[
'class' => TimestampBehavior::className(),
'updatedAtAttribute' => 'update_time',
'value' => new Expression('NOW()'),
],
You can also use
'value' => date('Y-m-d H:i:s')
if you would like to use the PHP datetime.
I used new Expression('NOW()') to store current timestamp. But It does't store the date based on current timezone. Instead it stores based on server time.
I just used normal php date function to solve this.
eg :
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
public function behaviors()
{
return [
'timestamp' => [
'class' => 'yii\behaviors\TimestampBehavior',
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
],
'value' => date('Y-m-d H:i:s'),
],
];
}
You must also add the value and use the class Expression
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
public function behaviors()
{
return [
'timestamp' => [
'class' => 'yii\behaviors\TimestampBehavior',
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
],
'value' => new Expression('NOW()'),
],
];
}