YII how to get relations - yii

I have two tables Center and Class. the relation between this Centerclass.
relation in Class,
'centers' => array(self::MANY_MANY, 'Center', 'centerclass(cl_id, cent_id)'),
and relation in Center,
'classes' => array(self::MANY_MANY, 'Class', 'centerclass(cent_id, cl_id)'),
Now if I have center id, how can I get all classes that associate with this Center.
Please give me criteria in Yii for this.
Thank you.

You can use the 'with()' method to apply a JOIN relation on the query:
$center = Center::model()->with('classes')->findByPk($centerId);
And get the classes with a foreach like this:
foreach($center->classes as $class){
echo $classes->cl_id; // Attribute that you like to show.
}
Edited:
To use in CGridView:
Controller:
$dataProvider = new CArrayDataProvider('Class');
$dataProvider->setData($center->classes);
Add $dataProvider in render to send it to the view.
More info in: http://www.yiiframework.com/doc/api/1.1/CDataProvider
Or directly in view:
$this->widget('zii.widgets.CListView', array(
'dataProvider'=>new CActiveDataProvider('Class', array(
'data'=>$center->classes)
),
....
More info in:
http://www.yiiframework.com/doc/api/1.1/CBaseListView

$center = Center::model()->with('classes')->findByPk($centerId);
foreach($center->classes as $class){
...
}

Related

FUELPHP ORM: Database view 'viewname' is defined without columns

I am using ORM in FuelPHP to fetch some data on a table view I created in my data base.
I followed the instruction that is given here but I'm getting an error as seen on the title above. Here is a screenshot of the error for reference (http://prntscr.com/72ssqc).
Here is the code:
http://pastebin.com/ips5VCzV
Here is a screenshot of the view Table:
http://prntscr.com/72st1e
Your view definition is wrong, it misses the 'columns' array, as the message explains.
protected static $_views = array(
'hugot_summary' => array(
'columns' => array(
'id',
'user_id',
'photo_id',
'hugot',
'url',
'comment_count',
'upvotes',
'created_at',
'updated_at'
),
),
);

yii CGridView show only logged-in user's records in many_many relation

I have two tables: user and asset and there is user_asset table that makes many_many relation
Now I want to show only the assets related with logged-in user in CGridView (user_id comes from Yii::app()->user->id)
How to write a criteria that makes it possible?
1) You need to define your relations in both of the model
user:
'assets' => array(self::MANY_MANY, 'Asset', 'user_asset(user_id, asset_id)'),
asset:
'users' => array(self::MANY_MANY, 'Asset', 'user_asset(asset_id, user_id)'),
2) You Create a dataProvider that will fetch only the recquired datas (define it in a model (best) or a controller bu not in a view):
$dataProvider=new CActiveDataProvider('Asset', array(
'criteria'=>array(
'with'=>array(
'users'=>array(
'condition' => 'id = ' . Yii::app()->user->id
),
),
),
...
));
3) You give to your CGridView the good provider:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
...
));
The code is given as example, you should adapt it to your need!
I got it work, adding this inside the Model class's search method:
$criteria->with=array(
'users'
);
$criteria->together = true;
$criteria->condition = "users_users.user_id='".Yii::app()->user->id."'";
... and inside CActiveDataProvider declaration:
'criteria'=>array(
'with' => 'users',
'together'=>true,
'condition'=>'users_users.user_id = '.Yii::app()->user->id,
),
Maybe not the best way but does what needed. users_users is sql table alias by Yii, I got a hint from error message :)

Yii CActiveDataProvider Join and select from joined table

I have the following example code:
$dataProvider = new CActiveDataProvider('firstTable',
array('criteria' => array(
'select' => 't.firstfield,secondTable.secondfield',
'join' => 'join secondTable on secondTable.id=t.secondTable_id',
),
'pagination' => array(
'pageSize' => 10,
),
));
$results=$dataProvider->getData();
After running the code above, firstField (from the model table - firstTable) is available in the object, but secondField (from the joined table - secondTable) is not.
Can anyone provide assistance on what is wrong with the code or why the "select" option is not picking up the secondField?
it would be better if you use CDbCriteria, that has a better solution to join table with the help of relations. I can show the example with CDbCriteria.
$criteria = new CDbCriteria;
$criteria->select = 'firstfield';
$criteria->with = array('secondTable_relation'=>array('select'=>'secondfield'));
$dataProvider = new CActiveDataProvider('firstTable',
array('criteria' => $criteria,
'pagination' => array(
'pageSize' => 10,
),
));
$results=$dataProvider->getData();
secondTable_relation is a relation name with secondTable.
Can anyone provide assistance on what is wrong with the code or why the "select" option is not picking up the secondField?
Answer:
That is happening because you have not selected the field which relates the two tables, i.e the foreign key in firstTable : secondTable_id. So if you do:
'select' => 't.firstfield,t.secondTable_id,secondTable.secondfield',
you will be able to access the secondField of secondTable:
$singleresultrow->secondTableRelationName['secondField'];// a single result row can be obtained by foreach iteration over $results
However there will still be another query (Lazy Loading) when you access the secondField. And the initial(before lazy) object returned will not have the secondTable object filled.
The problem i think lies in the fact that by default yii accesses the related fields by lazy loading, and for that to happen the related foreign_key should be present in the model you are trying to make a dataprovider of, here it is firstTable, and the foreign_key secondTable_id.

yii 'through' relation search

I have the following tables.
User:
---------
id<br>
firstName
Project:
---------
id<br>
Name
StaffingManager
---------------
id<br>
User_id(FK)<br>
Total_Staff<br>
StaffingProjectMonth
-----------------------
id<br>
Project_id(FK)<br>
StaffingManager_id(FK)<br>
I want to define the relations in StaffingProjectMonth model
This is the default relation defined by YII using gii
public function relations()
{
return array(
'project' => array(self::BELONGS_TO, 'Project', 'Project_id'),
'staffingManager' => array(self::BELONGS_TO, 'StaffingManager', 'StaffingManager_id'),
);
}
I was able to get the ProjectName and search by ProjectName.
I want to get the UserfirstName and search by that.
I defined the relation this way.
return array(
'project' => array(self::BELONGS_TO, 'Project', 'Project_id'),
'staffingmanager' => array(self::BELONGS_TO, 'StaffingManager', 'StaffingManager_id'),
'user'=> array(self::HAS_MANY,'User',array('User_id'=>'id'),'through'=>'staffingmanager' ),
);
and in search method I did this:
$criteria->with = array('project','user');
//$criteria->compare('id',$this->id);
$criteria->compare('Name',$this->Project_id,true);
$criteria->compare('firstName',$this->StaffingManager_id,true);
and in the view:
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'staffing-project-month-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
// 'id',
array('name'=>'Project_id','header'=>'Project','value'=>'$data->project->Name',),
array('name'=>'StaffingManager_id','header'=>'User','value'=>'$data->staffingmanager->user->firstName',),
..............
only the search by project name works. Able to sess the UserfirstName but unable to search by the firstName. Some wrong in defining relations.
Any help is appreciated. Thanks.
I recommend the following excellent wiki article by redguy, that describes how to search by related model attributes:
Following the approach of this article:
You should declare two new variables in your model:
public $project_name;
public $staffingmanager_firstname;
You should declare these new variables as safe for search in the rules() method:
array( 'project_name,staffingmanager_firstname,...', 'safe', 'on'=>'search' ),
Your search() method criteria should look like this:
$criteria->compare('project.Name',$this->project_name,true);
$criteria->compare('user.firstName',$this->staffingmanager_firstname,true);
In your view file, the 'columns' should be:
array('name'=>'project_name','header'=>'Project','value'=>'$data->project->Name',),
array('name'=>'staffingmanager_firstname','header'=>'User','value'=>'$data->user->firstName',),
Hope this helps.
Best regards...
I had troubles with $criteria->with and ”through“ relation.
Thing was in relation kind. BELONGS_TO doesn't work correct. I switched it to HAS_ONE and inverted id direction — array('parent_id'=>'id'). Now it's working!

CGridview and Yii Active Record Relation

I have two tables tbl_business and business_contacts of the following structure:
tbl_business
---
business_id (PK)
othercolumns
and
business_contacts
---
contact_id (PK)
business_id
othercolumns
The scenario is that one business row has many contacts. I am using cGridview using gii's CRUD generator and needed to display firstname and lastname from business_contacts (one of multiple possible rows in the table) for each tbl_business record.
As far as I understand, I've updated the relation function in tbl_business's model as:
'businesscontacts' => array(self::HAS_MANY,'BusinessContact','business_id','select' => 'contact_firstname, contact_lastname')
and for the same, a contact relation is defined in the business_contacts' model as:
'contactbusiness' => array(self::BELONGS_TO,'BusinessContact','business_id')
I expected that would work for pulling related records so that I can have something in the grid like, business_id, contact_firstname, contact_lastname , ... otherbusinesstablecolumns .. but I'm only getting blank values under firstname and lastname .. could someone please help me understand the error? :(
So you are trying to display a table of Businesses (tbl_business) using CGridView? And in each Business's row you want to list multiple Contacts (business_contacts)?
CGridView does not support displaying HAS_MANY relations by default. CGridView makes it easy to list which Business a Contact BELONGS_TO (i.e. you can use a column name like contactbusiness.business_id), but not all of the Contacts that are in a business.
You can do it yourself though, by customizing a CDataColumn. (Note: this will not allow you to sort and filter the column, just view. You'll have to do a lot more work in to get those working.)
First, in your Business model, add a method like this to print out all of the contacts:
public function contactsToString() {
$return = '';
foreach ($this->businesscontacts as $contact) {
$return .= $contact->contact_firstname.' '.$contact->contact_firstname.'<br />';
}
return $return;
}
(EDIT: Or do this to print out just the first contact):
public function contactsToString() {
if($firstContact = array_shift($this->businesscontacts)) {
return $firstContact->contact_firstname.' '.$firstContact->contact_firstname;
}
return '';
}
Then make a new column in your grid and fill it with this data like so:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'business-grid',
'dataProvider'=>$model->yourDataProviderFunction(),
'columns'=>
'business_id',
array(
'header'=>'Business Contacts', // give new column a header
'type'=>'HTML', // set it to manual HTML
'value'=>'$data->contactsToString()' // here is where you call the new function
),
// other columns
)); ?>
EDIT2: Yet another way of doing this, if you just want to print out ONE of a HAS_MANY relation, would be to set up a new (additional) HAS_ONE relation for the same table:
public function relations()
{
return array(
'businesscontacts' => array(self::HAS_MANY,'BusinessContact','business_id','select' => 'contact_firstname, contact_lastname') // original
'firstBusinesscontact' => array(self::HAS_ONE, 'BusinessContact', 'business_id'), // the new relation
);
}
Then, in your CGridView you can just set up a column like so:
'columns'=>array(
'firstBusinesscontact.contact_firstname',
),
Getting only the first contact could be achieved like this also:
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'business-grid',
'dataProvider'=>$model->yourDataProviderFunction(),
'columns'=>
'business_id',
//....
array(
'name' => 'contacts.contact_firstname',
'value' => '$data->contacts[0]->contact_firstname', // <------------------------
'type' => 'raw'
);
//....
),