i got this error when create date range search in search model.
Integrity constraint violation – yii\db\IntegrityException
SQLSTATE[23000]: Integrity constraint violation: 1052 Column
'created_at' in where clause is ambiguous
here's my model
public $start_date;
public $end_date;
public function rules()
{
return [
[['attachment', 'id_client', 'delete_on', 'created_at', 'created_by', 'updated_at', 'updated_by', 'from_location', 'to_location','printed_at', 'lock','verify','verify_by','approved','approved_by'], 'integer'],
[['policy_num'], 'autonumber', 'format'=>'formatPolicy'],
[['policy_num','premium_policy'], 'string'],
[['start_date','end_date'], 'date', 'format'=>'dd-MM-yyyy'],
[['from_location', 'to_location'], 'string', 'max' => 55],
[['location_address'], 'string', 'max' => 100],
[['attachment'], 'required'],
[['deductible'], 'string', 'max' => 100],
[['lock'], 'default', 'value' => '0'],
[['lock'], 'mootensai\components\OptimisticLockValidator']
];
}
here's my search model
public function rules()
{
return [
[['id', 'policy_num', 'attachment', 'id_client', 'delete_on','created_by', 'updated_by', 'printed_at'], 'integer'],
[['cover_rate'], 'number'],
[['start_date','end_date','created_at','updated_at'], 'date','format'=>'yyyy-mm-dd'],
];
}
public function search2($params)
{
$query = AskPolicy::find();
$query->joinWith(['client'])->where(['id_client'=>Yii::$app->user->identity->id_client]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'policy_num' => $this->policy_num,
'ask_policy.created_at' => $this->created_at,
'ask_policy.updated_at' => $this->updated_at,
'printed_at' => $this->printed_at,
]);
// $query->andFilterWhere(['>=', 'ask_policy.created_at', $this->start_date]);
// $query->andFilterWhere(['<=', 'ask_policy.created_at', $this->end_date]);
$query->andFilterWhere(['like',"(date_format(FROM_UNIXTIME(`created_at` ), '%Y-%m-%d' ))", $this->start_date])
->andFilterWhere(['like', "(date_format(FROM_UNIXTIME(`updated_at` ), '%Y-%m-%d' ))", $this->end_date]);
return $dataProvider;
}
if i use below code : search start date and end date not working
$query->andFilterWhere(['>=', 'ask_policy.created_at', $this->start_date]);
$query->andFilterWhere(['<=', 'ask_policy.created_at', $this->end_date]);
how to the best way convert integer datetime in Yii2 for date range search ? i was searching but not find tutorial with good explanation.
your query is joined with client and both models has created_at field.
you can set alias for current model with
$query->alias('t');
and alias joined table with
$query->joinWith(['client as cli']);
then if you want to use created_at from main model you can use t.created_at and if you want to use created_at from joined model you can use cli.created_at.
you have not given table alias try like this
$query->andFilterWhere(['like',"(date_format(FROM_UNIXTIME(ask_policy.`created_at` ), '%Y-%m-%d' ))", $this->start_date])
->andFilterWhere(['like', "(date_format(FROM_UNIXTIME(ask_policy.`updated_at` ), '%Y-%m-%d' ))", $this->end_date]);
Related
Is there any way to limit n number of contents in yii model any my code is
public function rules()
{
return [
[['id', 'editedby', 'cat_id', 'prod_id', 'parent', 'order', 'status'], 'integer'],
[['name', 'content', 'excerpt', 'date', 'url', 'posttype'], 'safe'],
];
}
/**
* #inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = Posts::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params,'');
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'date' => $this->date,
'editedby' => $this->editedby,
'cat_id' => $this->cat_id,
'prod_id' => $this->prod_id,
'parent' => $this->parent,
'order' => $this->order,
'status' => $this->status,
]);
$query->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'content', $this->content])
->andFilterWhere(['like', 'excerpt', $this->excerpt])
->andFilterWhere(['like', 'url', $this->url])
->andFilterWhere(['like', 'posttype', $this->posttype]);
return $dataProvider;
}
it was a model to list products if the user was in free plan have to show only one product or else have to display products based on plan count will change i have no idea that how to add the condition i need something like
if($user_type==1){
$query->andFilterWhere([['id' => SORT_DESC])->one();]);
}
As Raul Sauco already mentioned you could use something like that
$query->andFilterWhere([['id' => SORT_DESC])->limit($user_type == 1 ? 1 : 20);
I've an gridView for showing data. GridView table has a column that called as Created By, this column contain the ID of User that I get from user table. Basicly, this column will show data as Integer(ID) like this:
But I've set code like this to show the username of the ID:
[
'attribute' => 'created_by',
'format' => 'raw',
'value' => function ($data) {
$modelUser = Users::find()->where(['id' => $data->created_by])->one();
$nama = $modelUser->username;
return $nama;
},
'vAlign' => 'middle',
'hAlign' => 'center',
],
Result:
The gridView has filter column, I'm trying to filter data based on inserted value. I'm trying input username as the value for filtering but it give an error message "created By must be an Integer", like this:
How do I can filtering that column using the a username(varchar)?
Thanks
Update
This is my searchModel.php
<?php
namespace app\search;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Product;
/**
* ProductSearch represents the model behind the search form of `app\models\Product`.
*/
class ProductSearch extends Product {
/**
* #inheritdoc
*/
public function rules() {
return [
[['productId', 'userId', 'parentId', 'created_by'], 'integer'],
[['date', 'created_at', 'name', 'address'], 'safe'],
[['price'], 'number'],
];
}
/**
* #inheritdoc
*/
public function scenarios() {
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params) {
$query = Product::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'productId' => $this->productId,
'price' => $this->price,
'created_at' => $this->created_at,
'created_by' => $this->created_by,
]);
$query->andFilterWhere(['MONTH(date)' => $this->date])
->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'address', $this->address]);
return $dataProvider;
}
}
public function rules()
{
return [
[['productId', 'userId', 'parentId'], 'integer'],
[['date', 'created_at', 'name', 'address'], 'safe'],
[['price'], 'number'],
[['created_by'], 'string'],
];
}
public function search($params)
{
$query = Product::find()->joinWith('createdBy'); // Whatever relation name
.
.
.
.
.
// grid filtering conditions
$query->andFilterWhere([
'productId' => $this->productId,
'price' => $this->price,
'created_at' => $this->created_at,
]);
$query->andFilterWhere(['MONTH(date)' => $this->date])
->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'address', $this->address])
->andFilterWhere(['like', 'userTableName.username', $this->created_by]); // Whatever table name and field name.
return $dataProvider;
}
You should add a proper filter to your column
[
'attribute'=>'your_attribute',
......
'filter'=>ArrayHelper::map(YourModel::find()->asArray()->all(),
'your_id_column', 'your_name_column'),
],
I have a table which has a field `activated_at` timestamp NULL DEFAULT NULL, which means that it can contain a timestamp or it can be null and it's null by default.
I have another [gii-generated] search model with a following configuration in the search() method:
public function search($params)
{
$query = User::find();
// add conditions that should always apply here
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$andFilterWhere = [
'id' => $this->id,
'status' => $this->status,
'role' => $this->role,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'completed_files' => $this->completed_files,
// 'activated_at' => null,
];
if(!isset($_GET['deleted'])) {
$query->where(['deleted_at' => null]);
$andFilterWhere['deleted_at'] = null;
} else if($_GET['deleted'] === 'true') {
$query->where(['not', ['deleted_at' => null]]);
}
// grid filtering conditions
$query->andFilterWhere(
$andFilterWhere
);
$query->andFilterWhere(['like', 'first_name', $this->username])
->andFilterWhere(['like', 'auth_key', $this->auth_key])
->andFilterWhere(['like', 'password_hash', $this->password_hash])
->andFilterWhere(['like', 'password_reset_token', $this->password_reset_token])
->andFilterWhere(['like', 'email', $this->email])
->andFilterWhere(['like', 'first_name', $this->first_name])
->andFilterWhere(['like', 'last_name', $this->last_name]);
if($this->activated || $this->activated === "0") {
#die(var_dump($this->activated));
if($this->activated === '1') {
// this doesn't filter
$query->andFilterWhere(['not', ['activated_at' => null]]);
} else if($this->activated === '0') {
// this doesn't either
$query->andFilterWhere(['activated_at', null]);
}
}
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
return $dataProvider;
}
Yes, I have set the activated property in my class:
public $activated;
And my rules() method is as following:
public function rules()
{
return [
[['id', 'status', 'role', 'created_at', 'updated_at', 'completed_files'], 'integer'],
['activated', 'string'],
[['username', 'first_name', 'last_name', 'auth_key', 'password_hash', 'password_reset_token', 'email', 'deleted_at', 'completed_files', 'activated_at'], 'safe'],
];
}
What I was trying to set in the search() method is to filter on field activated_at depending on the $activated value (see above code):
if($this->activated || $this->activated === "0") {
#die(var_dump($this->activated));
if($this->activated === '1') {
// this doesn't filter
$query->andFilterWhere(['not', ['activated_at' => null]]);
} else if($this->activated === '0') {
// this doesn't either
$query->andFilterWhere(['activated_at', null]);
$andFilterWhere['activated_at'] = null;
}
}
I use it with GridView - every other filter works except this one.
What am I doing wrong here?
Aand how to properly do this sort of queries:
IS NULL something
IS NOT NULL something
With Yii 2's ActiveRecord query builder?
EDIT: Line: if(!isset($_GET['deleted'])) is used for something else and this works normally.
If i understand right you can use andWhere
->andWhere(['not', ['activated_at' => null]])
but andFilterWhere in execute where the related value is not null
from doc http://www.yiiframework.com/doc-2.0/yii-db-query.html
andFilterWhere() Adds an additional WHERE condition to the
existing one but ignores empty operands.
for this expression:
WHERE activated_at IS NULL
try this (it's working):
->andWhere(['is', 'activated_at', new \yii\db\Expression('null')]),
$null = new Expression('NULL');
$query->andFilterWhere(['is not', 'asp_id', $null]);
OR
$query->andFilterWhere(['is', 'asp_id', $null]);
this solution check if column_name is empty or NULL
WHERE (LENGTH(`column_name`) > 0)
->andWhere(['>', 'LENGTH(column_name)', 0]) //check if empty or null
Another variant - check only for NULL
WHERE column_name IS NOT NULL
->andWhere(['IS NOT', 'column_name', null]); // check on null
// ...WHERE (`status` = 10) AND (`type` IS NULL) AND (`info` IS NOT NULL)
$query->where([
'status' => 10,
'type' => null,
])
->andWhere(['not', ['info' => null]]);
i have id there is PK(Auto Inc) from models/order relation with FK id_order from models/preorder, In my CRUD action for example actionCreate, i can't insert attibutes preorder to table because id(PK) from order always null. how do i fix this ?.
here's my controller
$cartPositions = Yii::$app->cart->getPositions();
if (!$cartPositions or $cartPositions === null) {
return $this->redirect(['index']);
}
$dataProvider = new ArrayDataProvider([
'allModels' => $cartPositions,
]);
$model = new Order();
$model_po = new Preorder();
$postData = Yii::$app->request->post();
if ($model->load($postData) && $model_po->load($postData)) {
//model->save(false);
$model->status = 5;
$model_po->id_order = $model->id;
$model->total_cost = Yii::$app->cart->getCost();
$model->date = date('Y-m-d H:i');
$model->data = Yii::$app->cart->getSerialized();
$model_po->name = $model->name;
$model_po->phone = $model->phone;
$model_po->remarks = $model->message;
$model_po->created_at = $model->date;
//$model_po->save();
if (Model::validateMultiple([$model, $model_po]) && $model->save(false) && $model_po->save()) {
Yii::$app->session->setFlash('success', 'Thank You');
Yii::$app->mailer->compose('order/html', [
'model' => $model,
//'model_po' => $model_po,
'dataProvider' => $dataProvider,
])
//->setFrom(Yii::$app->params['email']['from'])
// ->setTo(Yii::$app->params['email']['to'])
// ->setSubject('The site posted a new order')
// ->send();
->setFrom(Yii::$app->params['email']['from'])
->setTo(Yii::$app->params['email']['to'])
->setSubject('The site posted a new Preorder')
->send();
Yii::$app->cart->removeAll();
return $this->render('orderSuccess', [
'model' => $model,
//'model_po' => $model_po,
]);
}
} else
{return $this->render('create_po', [
'model' => $model,
'model_po' => $model_po,
'dataProvider' => $dataProvider,
]);}
}
models/order
public function rules()
{
return [
[['status', 'total_cost', 'date', 'data', 'name', 'phone'], 'required'],
[['code_order'], 'autonumber', 'format'=>'orderNum', 'digit'=>4],
[['status', 'total_cost'], 'integer'],
[['date'], 'safe'],
[['data', 'message'], 'string'],
[['name', 'email', 'phone'], 'string', 'max' => 255]
];
}
model/preorders
public function rules()
{
return [
[['id_order', 'address'], 'required'],
[['id_order'], 'integer'],
[['created_at', 'updated_at'], 'safe'],
[['address', 'remarks'], 'string', 'max' => 500],
[['id_order'], 'exist', 'skipOnError' => true, 'targetClass' => Order::className(), 'targetAttribute' => ['id_order' => 'id']],
];
}
error info :
Integrity constraint violation – yii\db\IntegrityException
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'id_order' cannot be null
The SQL being executed was: INSERT INTO preorder (address, id_order, name, phone, remarks, created_at) VALUES ('', NULL, 'Name', '121324325', '', '2016-07-23 17:01')
Error Info: Array
(
[0] => 23000
[1] => 1048
[2] => Column 'id_order' cannot be null
i was try getPrimaryKey() and last insert id() not work and i was try to remove $modelpo->id_order = $model->id the result is two tables filled but id_order is 0
$model->id is null until successful $model->save() so you should not assign its value to $model_po->id_order before that.
This is a good place for transaction so you can validate data first, then make sure Order is saved and then save Preorder with proper id_order.
Take a look at link() method as well.
why don't you use afterSave()? it will definetely solve your problem
I have two collections - Users and Order
I have a list of orders(OrderSearch model) with some users details(email, name..). Now I want to search user details relationally.
OrderSearch Model---
public function search($params)
{
// Email getting from query params
if(!empty($params['email'])){
$this->email = $params['email'];
}
$query = Order::find();
$query->with(['user']); // for related document
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pagesize' => 10,
],
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'id' => isset($this->id)?(int)$this->id:$this->id,
'status' => $this->status,
'user_id' => $this->user_id,
]);
$query->andFilterWhere(['like', 'sku', $this->sku])
->andFilterWhere(['like', 'message', $this->message])
// Tried below code but it is not working.
->andFilterWhere(['like', 'user.email', $this->email]); // $this->email is email which I want to search
return $dataProvider;
}
Relation in Order Model -
public function getUser(){
return $this->hasOne(User::className(), ['_id' => 'user_id']);
}