Yii Criteria: condition for relation - yii

i have two tables: User and User_works (User HAS_MANY User_works).
How can I add a condition to be displayed only users with certain works
User contains fields: id | name | Other information
User_works: id | user_id | work_id
User Model:
public function relations()
{
return array(
'works'=>array(self::HAS_MANY, 'UserWorks',
'',
'on' => 'works.user_id=t.id',
'together'=>false,
),
)
}
Controller:
$criteria = new CDbCriteria();
$criteria->with = array('works');
$criteria->compare = ????

Solution:
I wanted something like that:
SQL "Select user.id from User, User_works Where User_works.user_id=User.id AND User_works.work_id=$SOMEVALUE"
User Model:
public function relations()
{
return array(
'works'=>array(self::HAS_MANY, 'UserWorks',
'',
'joinType' => 'INNER JOIN',
'on' => 'works.user_id=t.id',
'together'=>true,
),
)
}
Controller:
$criteria = new CDbCriteria();
$criteria->with = array('works'=>array('on' => 'works.user_id=t.id AND (works.work_id=$SOMEVALUE OR ...)'));
As a result, I get the users with the necessary works.
But а new problem arose. The number of pages in the Listview not correctly displays.
List view does not consider the condition of necessary works. As a result, a number of page is wrong.
Solution :
$dataProvider=new CActiveDataProvider('User', array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>1,
),
));
$dataProvider->setTotalItemCount(count(User::Model()($criteria)));
or
Instead of setting the dataprovider criteria:
$dataProvider->criteria = $criteria
I set dataprovider->model criteria:
$dataProvider->model->setDbCriteria($criteria)

$criteria = new CDbCriteria();
$criteria->with = array('works');
$criteria->compare('works.theField_name' , $someThing);

Related

Yii Cgridview filter not working?

I am trying to implement a dropdown filter in Cgridview, The column is from another table.
//model search code
//person table
public function search(){
$criteria=new CDbCriteria;
$criteria->alias='per';
$criteria->compare('LastName',$this->LastName,true);
$criteria->compare('FirstName',$this->FirstName,true);
$criteria->join='right JOIN person_surveys ps ON ps.id = per.P_Id';
}
//relation to person survey
public function relations()
{
return array(
'user' => array(self::BELONGS_TO, 'PersonSurvey', 'P_Id'),
);
}
//person survey table model search
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('person_id',$this->person_id,true);
$criteria->compare('survey_ids',$this->survey_ids,true);
$criteria->join='left JOIN persons ps ON ps.id = per.P_Id';
}
//controller
public function actiongriddisplay(){
$model2=new Persons('search');
if(isset($_GET['ajax'])){
$model2->attributes =$_GET['Persons'];
$this->render('griddisplay',array('model2'=>$model2));
}
else{
$this->render('griddisplay',array('model2'=>$model2));
}
}
//in view file
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $model2->Search(),
'filter' => $model2,
'ajaxType'=>'GET',
// 'ajaxUpdate'=>'items',
//'ajaxUrl' =>$this->createUrl('userManagement'),
'columns' => array(
array(
'name' => 'FirstName',
'header'=>'Full Name',
),
array(
'name' => 'user.survey_ids',
'header'=>'Survey ids',
'filter'=>CHtml::activeDropDownList($model2 ,'survey_ids', array('224'=>'224','223'=>'223','225'=>'225')),
'value'=>'isset($data->user->survey_ids)?$data->user->survey_ids:null'
),
I have put the search on, in models. why is the dropdown filter not working?
Why this is not working please help?
This link (http://www.yiiframework.com/wiki/281/searching-and-sorting-by-related-model-in-cgridview/) will solve your problem.

How create condition to relations Yii

I have relations in Yii:
public function relations() {
return array(
'applicant' => array(
self::BELONGS_TO,
'ApplicantProfile',
array('applicant_id' => 'id'),
),
'filePair' => array(
self::BELONGS_TO,
'DocumentCategoryFile',
array('file_pair_id' => 'id'),
'joinType' => 'inner join'
)
);
}
How i can create addCondition in CDbCriteria() for aplicant, for example i want do is_deleted = 0. I am tried it $criteria->with = array('applicant' => array('join'=>'left join','condition'=>'aplicant.is_deleted = 0')); but i have sql syntax error
Thanks
Try this -
$criteria = new CDbCriteria();
$criteria->with = array('applicant');
$criteria->together = true;
$criteria->addCondition('applicant.is_deleted=0');
You should refer the link here to learn how to use it.

How to show other model field in my cgridview

I want to show a other model field in my cgrid view , I am using yii model.
My current model is Members and other model is Billing:
My Code:
public function getImportantMembers(){
$criteria = new CDbCriteria;
$criteria->select ='t.*,b.billing_id,b.amount,b.billing_date,b.member_id,b.billing_status';
$criteria->join = 'JOIN billing AS b ON b.member_id = t.id ';
if(isset($_GET['condition']) AND $_GET['condition'] > 0){
$condition = $this->getConditionForImportantMembers($_GET['condition']);
$criteria->addCondition($condition);
}
else{
$criteria->addCondition("b.billing_date > DATE_SUB(NOW(),INTERVAL 2 MONTH) AND b.billing_status='c' AND b.amount >= 150 AND t.status='a'");
}
$criteria->group = 't.id';
return new CActiveDataProvider(get_class($this), array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=> Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize']),
),
));
}
You should first clear the relation in your member model;
'billing' => array(self::BELONGS_TO, 'Billing', 'id'),
In your view:
$data->billing->amount

Yii Model with combined tables using relations in Active Record

I've got the model class Contactindiv with relations and search as follows.
public function relations()
{
return array(
'contactlogs' => array(self::HAS_MANY, 'Contactlog', 'ContactIndivID'),
);
}
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('ContactIndivID',$this->ContactIndivID);
$criteria->compare('PersonalTitle',$this->PersonalTitle,true);
$criteria->compare('NameLast',$this->NameLast,true);
$criteria->compare('NameMiddle',$this->NameMiddle,true);
$criteria->compare('NameFirst',$this->NameFirst,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
The current page shows the data in a searchable CGridView format.
My goal is to combine the 'contactlogs' from relations into the Model in order to have it show up on the page in a searchable fashion in the GridView. Basically add a searchable GridView column for each contact showing their contact log.
Thanks ahead of time for your help!
For your first goal (show contactlogs in model) you can write a getter in your main model. It depends, what you want to show in your gridview column but you could use something like:
public function getContacts()
{
$names = array();
foreach($this->contactlogs as $log)
$names[] = $log->name;
return implode(', ', $names);
}
Now you can use contacts as if it where a regular attribute of your "Contactindiv" model.
For your second goal you could add a public property which will contain the filter value, and which you can use in your search() method:
public $contactFilter;
public function search()
{
// ...
if(!empty($this->contactFilter)) {
$criteria->with = array(
'contactlogs' => array(
'joinType' => 'INNER JOIN',
'on' => 'contactlogs.name = :name',
),
);
$criteria->params[':name'] = $this->contactFilter;
}
// ..
}
Now you only need to add all the above in your gridview's columns configuration:
array(
'name' => 'contacts',
'filter' => CHtml::activeTextField($model, 'contactFilter'),
)
Please note, that i'm writing most of this from the top of my head and couldn't fully test it. But it should hopefully make the basic concept clear to you. Please let me know if it works.

Relationship issue in YII

I Have a GetStudents function in Agent model. where I fetch the students related to the agents.
But I want to show more fields of students from another table
Eg
**Agent table** (agent has students)
agent_id
**student table**
STUDENTID pkey
agent_id
**relation table** (this table creates relation between student and household)
StudentID HOUSEHOLDID
**HOUSEHOLD TABLE**
HouseHOLDID Householdname
I want to fetch householdname when I fetch all student details.
really looking bazzare to me as I am newbie to YII
MY function in agent model.
public static function getStudents($id) {
$relationships = Relationship::model()->findAll('type = :type AND source = :agent_id', array(':type' => 2, ':agent_id' => $id));
//$relationships=sort($relationships);
// Generate relationship array
//print_r($relationships);
foreach ($relationships as $relationship) {
$in[] = $relationship->destination;
}
// Generate db condition
$criteria = new CDbCriteria;
if (! isset($in) || ! is_array($in) || sizeOf($in) == 0) {
$in[] = -999;
}
$criteria->addInCondition('StudentID', $in, 'OR');
return new CActiveDataProvider('Student', array(
'criteria' => $criteria,
'sort'=>array('defaultOrder'=>array(
'StudentID'=>CSort::SORT_DESC,
)),
));
}
My code to fetch data in by passing ID into it
<?php $this->widget('zii.widgets.CDetailView', array(
'data' => $model,
'attributes' => array(
array(
'label' => 'Agent Details',
'type' => 'raw',
'value' => '',
'cssClass' => 'heading',
),
'agent_id',
'user.email',
'first_name',
'last_name',
'company',
'phone',
),
)); ?>
Any help would be greatly appreicated.
Thanks
Ab
First you should make relation with student to relation table in relations array in relation model like this ..
'student'=>array(self::BELONGS_TO, 'Student', 'StudentID'), //after belongs to student is model class name
'household'=>array(self::BELONGS_TO, 'HOUSEHOLD', 'HOUSEHOLDID'),//after belongs to HOUSEHOLD is model class name
And then you can fetch all record with active record like this...
$relationships = Relationship::model()->with('student','household')->findAll('type = :type AND source = :agent_id', array(':type' => 2, ':agent_id' => $id));