Yii dataprovider criteria for today's date - yii

I want to display only the data in the dataprovider for today's date only. $data->timedate is the appointment date. If it is equal to the current date, display it. The following code does not work.
//today appointments dataprovider
$taProvider=new CActiveDataProvider('Appointments',array(
'sort'=>array(
'defaultOrder'=>'datetime ASC',
),
'criteria'=>array(
'condition'=>'cId=:cId',
'params'=>array(':cId'=>Yii::app()->user->id),
'condition'=>$data->timedate = date('Y-m-d'),
),
));

EDIT Modifiyed for using CDbcriteria object
You are using the PHP variables within CDbCriteria->condition. CDbCriteria Condition is nothing but the where clause in your sql query http://www.yiiframework.com/doc/api/1.1/CDbCriteria#condition-detail
Also your second assignment would overwrite the first if you need to add condition you need to use addCondition() method
Change
'criteria'=>array(
'condition'=>'cId=:cId',
'params'=>array(':cId'=>Yii::app()->user->id),
'condition'=>$data->timedate = date('Y-m-d'),
),
to
'criteria'=>array(
'condition'=>"DATE(t.timedate) = DATE(NOW()) AND cId=:cId ",
'params'=>array(':cId'=>Yii::app()->user->id),
),

Related

"andFilterWhere" work proper with "joinWith()" but not with "with()" in yii2

I am working in yii2.
There are employee and company table employee contains company_id.
I have a filter search running properly If I use joinWith()
$query = Employee::find();
$query->joinWith(['company']);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => false,
'sort' => false,
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
//and below is the filterwhere
$query->andFilterWhere(['like', 'company.name', $this->company_id]);
But issue came when I make a query using with()
$query = Employee::find()->with(['company']);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => false,
'sort' => false,
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
//when query contain with() then this filter is not working.
$query->andFilterWhere(['like', 'company.name', $this->company_id]);
This gives error when I use with()
Database Exception – yii\db\Exception
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'company.name' in 'where clause'
The SQL being executed was: SELECT COUNT(*) FROM `employee` WHERE `company`.`name` LIKE '%1%'
Here is the relation in employee with company:
public function getCompany(){
return $this->hasOne(Company::className(), ['id'=> 'company_id']);
}
Can anyone help me or guide me how could I filter data properly using with() in a query?
Thanks.
You can't swap joinWith() and with() methods when you need to filter by the column from the related table. That's because these methods does completely different things.
Methods like joinWith() and join() actually modifies the query to add the "JOIN" part to the SQL query. The with in joinWith allows you to specify the joined table by the relation definition in the model. The eager loading in joinWith is only side effect and you can even turn that off by passing false as second parameter.
When you do:
Employee::find()->joinWith(['company'])->all();
The query that is run looks like:
SELECT * FROM employee LEFT JOIN company ON (...)
On the other side the method with() doesn't modify the query itself. It only forces the eager loading of related models. In reality the second query is used for preloading the related records.
When you do:
Employee::find()->with(['company'])->all();
It actually runs queries like these:
SELECT * FROM employee;
SELECT * FROM company WHERE id IN (...company ids selected in first query...);
So when you try to do:
$query = Employee::find()
->with(['company'])
->andFilterWhere(['like', 'company.name', $this->company_id])
->all();
The generated query is
SELECT * FROM employee WHERE company.name LIKE ...

Yii CDbCriteria get all records with same character in column

i'm not good with sql, i'm making a CListView for all records with a selected id in column to be displayed on the page.. just for practice, i wanted to add a dropdown that will select another kind of sort (id DESC is already there).
i have a table with columns: id, Name, Project_id, User_id, Assigned, etc...
for now this is my code:
public function actionView($id)
{
$model = $this->loadModel($id);
$criteria = new CDbCriteria(array(
'order'=>'id desc',
'condition'=>'Project_id='.$id
));
$dataProvider = new CActiveDataProvider('Task', array(
'criteria'=>$criteria
));
$this->layout = 'column2';
$this->render('view', array('model'=>$model, 'dataProvider'=>$dataProvider));
}
i'm selecting all records that has the requested project_id, so what i'm trying to do, which i have no clue how to do, is to add another criteria selection on the column "Assigned" the problem is, some of this records has more than 1 single assigned and its being saved as "1,2,5,6". so if i add another selection with assigned 1, it will just show me thoses records that have in assigned "1" and not thoses that have "1,3,5,6".. i was thinking on make a search on string but i dont know how it works on sql (Because i dont know SQL that much)
Try this -
$criteria = new CDbCriteria(array(
'order'=>'id desc',
'condition'=>'Project_id='.$id.' AND find_in_set($assigned, Project_id)'
));
But here $assigned can have only single value i.e. $assigned = 1 or $assigned = 2.
If $assigned = "1,2" where 1,2 itself will be considered as single value and so result will be returned only if the pattern is 1,2.. in the table and not 2,1,...
I hope it gives some idea.
found my solution.. seems like im using SQLite and SQLite does not support find_in_set(), instead. i would have to use (',' || Assigned || ',') LIKE '%,1,%'. like this..
$criteria = new CDbCriteria(array(
'order'=>'id desc',
'condition'=>'Project_id='.$id.' AND ("," || Assigned || ",") LIKE "%,5,%"'
));

How to avoid date-picker displaying default date (12/31/1969)?

I've tried defaultDate="" property but it doesn't show even if I gave some value to the date picker?
Here's my datepicker code:
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'model'=>$model,
'attribute'=>'date_healed',
'value'=>$date_healed,
'name'=>'date_healed'.$i,
// additional javascript options for the date picker plugin
'options'=>array(
//'autoSize'=>true,
'defaultDate'=>"",
'changeMonth'=>'true',
'changeYear'=>'true',
'yearRange'=>Yii::app()->params['YearRange'],
),
'htmlOptions'=>array('size'=>'10')
));
Make sure you delete default value from database table
if you see the table structure ... if you see like this, then remove '0000-00-00'
....
`date_healed` date NULL DEFAULT '0000-00-00',
....
should be...
....
`date_healed` date NULL,
....

Using with and together in Yii

I have a grid with paging which displays client data.
Let's say I have a table Client with name, lastName and address in it, a table Phone_Number which has phone numbers for each of the rows in Client and a table Adress which has adresses for each client. So each Client HAS MANY Phone_Numbers and HAS MANY Adresses.
The point is I'm trying to set a limit to the grid's store read.
So let's say I set limit = 2. The grid should display only 2 rows per page (2 clients).
The problem is that if, for example, client1 has two phone numbers, the query will bring two rows, making the grid display only one client. I am aware that setting together=>false in the query will solve this. But I'm getting an unknown column error whenever I set together=>false.
Here's the code I'm using....
Client::model()->with(
'clientPhoneNumbers',
'clientPhoneNumbers'.'PhoneNumber',
'clientAddresses',
'clientAddresses'.'Address'
)->findAll(array(condition=>(('Address.s_street_name LIKE :queryString') OR ('PhoneNumber.n_number LIKE :queryString')), params=>$params, order=>$order, limit=>$limit,together=>false));
If I do this, I get an error like: Column not found: Address.s_street_name . However, if I set together=>true, it works just "fine".
I found a solution to this problem by doing the query like this....
$with = array(
'clientPhoneNumbers',
'clientPhoneNumbers'.'PhoneNumber'=>array(condition=>('PhoneNumber.n_number LIKE :queryString'), params=>array(':queryString'=>$queryString)),
'clientAddresses',
'clientAddresses'.'Address'=>array(condition=>('Address.s_street_name LIKE :queryString'), params=>array(':queryString'=>$queryString))
);
Client::model()->findAll(array(with=>$with, order=>$order, limit=>$limit,together=>false));
The problem is that if I do it like this, the condition is something like this
(('Address.s_street_name LIKE :queryString') AND ('PhoneNumber.n_number LIKE :queryString'))
and I need it to be like this
(('Address.s_street_name LIKE :queryString') OR ('PhoneNumber.n_number LIKE :queryString')).
Any ideas ?
Keep in mind that the names of the relations and tables are not the actual names. The models and relations where created using Gii
Hmm.. this is how I would try it.
<?php
$criteria=new CDbCriteria;
$criteria->with = array('clientPhoneNumbers', 'clientAddresses');
$criteria->together = true;
$criteria->addCondition(array('Address.s_street_name LIKE :queryString', 'PhoneNumber.n_number LIKE :queryString'), 'OR');
$criteria->params = array(':queryString' => $queryString);
$criteria->limit = $limit;
$criteria->order = $order;
$result = Client::model()->findAll($criteria);
?>
Also, I think this describes a case similar to yours. Note that he/she is updating the condition parameter explicitly, but IMO doing it with the addCondition method is more readable.
use criteria with join statement.
public function test()
{
$criteria=new CDbCriteria;
$criteria->alias = 'i';
$criteria->compare('id',$this->id);
.........
.........
$criteria->join= 'JOIN phoneNUmbers d ON (i.id=d.id)';
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=>array(
'defaultOrder'=>'clients ASC',
),
));
}
Alternately use DAO to prepare and execute your own query and return data in the format you wish.
Or you can use CSQLDataProvier. the last 2 options give you more control over the SQL statement

'OR' in NHibernate Lambda Extensions

How can I union two criteria with an OR statement?
For example I want to get Employee which has null in Birthday field OR value of this field is less than someDate. How should I rewrite this code:
var query = DetachedCriteria.For<Employee>()
.Add(SqlExpression.IsNull<Employee>(p => p.Birthday))
.Add<Employee>(emp => emp.Birthday.Value < someDate);
You need to use Disjunction()