What's the difference between ActiveDataProvider and SQLDataProvider? - yii2

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,
]
],
]);

Related

yii2:my dataprovider not sort true

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

Log not working in yii2

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.

Yii2 apply parameters to DB sort

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,
],
],
...

Yii2 : Cannot Show Data in Widget GridView

I try to show data from database in view using gridview, but i got problem
error message
Unknown Method – yii\base\UnknownMethodException
Calling unknown method: yii\db\ActiveQuery::getCount()
my controller
public function actionIndex()
{
$sql = "SELECT presensi.presensi_tanggal 'tanggal', sum(if( hadir.keteranganhadir_id='1',1,0)) 'hadir', sum(if( hadir.keteranganhadir_id='2',1,0)) 'tidak_hadir', count(*) 'total' FROM hadir, keteranganhadir, presensi where hadir.keteranganhadir_id = keteranganhadir.keteranganhadir_id and hadir.presensi_id = presensi.presensi_id group by presensi.presensi_tanggal";
$model = Hadir::findBySql($sql)->all();
return $this->render('index', [
'hadir' => $model,
]);
}
my view
<?= GridView::widget([
'dataProvider' => $hadir,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'tanggal',
'hadir',
'tidak_hadir',
'total',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
How can i fix the problem?
Gridview looks for dataprovider, not array of activerecord models you have sent:
http://www.yiiframework.com/doc-2.0/yii-data-sqldataprovider.html
in your controller/actionIndex
$count = Yii::$app->db->createCommand('
SELECT COUNT(*) FROM user WHERE status=:status
', [':status' => 1])->queryScalar();
$dataProvider = new SqlDataProvider([
'sql' => 'SELECT * FROM user WHERE status=:status',
'params' => [':status' => 1],
'totalCount' => $count,
'sort' => [
'attributes' => [
'age',
'name' => [
'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
'default' => SORT_DESC,
'label' => 'Name',
],
],
],
'pagination' => [
'pageSize' => 20,
],
]);
return $this->render('index', [
'hadir' => $dataProvider,
]);
You can try this:
In Controller.php file:
public function actionIndex()
{
$searchModel = new InvoiceSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Your view file seems to be true. Just add above code in your controller file.

TimestampBehavior is not working in Yii2

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()'),
],
];
}