I'm still new to Yii, but I'm trying to use relations() to join two tables and get all data from both table on each row pulled.
tables:
TABLE Artist KEYS(artist_Id, firstName, lastName)
TABLE Album KEYS(album_Id, title, artist_Id, genre)
// Album
public function relations()
{
return array(
'artist' => array(self::BELONGS_TO, 'Artist', 'artist_Id'),
'track' => array(self::HAS_MANY, 'Track', 'track_Id')
);
}
// Artist
public function relations()
{
return array(
'album' => array(self::HAS_MANY, 'Album', 'album_id')
);
}
// logic for getting information
$dataProvider=new CActiveDataProvider('Album');
foreach($dataProvider->getData() as $key){
echo '<br>' . $key->artist_Id; // does work
echo '<br>' . $key->firstName; // doesn't work
}
With this code, I can get and display the correct artist_Id for the album. However, I want to display the artist firstName and lastName with the artist_Id.
I needed to change my $dataProvider variable and how I was trying to access in the view index.php
$dataProvider = new CActiveDataProvider('Album');
-to-
$dataProvider = new CActiveDataProvider('Album', array('criteria' => array('with' => array('artist'))));
and changing view index.php to one of the two:
'name' => 'artist.lastName',
or
'value' => '$data->artist->firstName'
Related
I have a HAS_MANY relation between 2 models, i use bookID as foreign key
model 1 - Importedbooks, Importedbooks can have many CountryOfImport
public function relations()
{
return array(
'CountryOfImportObj'=>array(self::HAS_MANY, 'CountryOfImport', 'bookID')
);
}
model 2 CountryOfImport, CountryOfImport belongs to Importedbooks
public function relations()
{
return array(
'ImportBooksObj'=>array(self::BELONGS_TO, 'Importedbooks', 'bookID')
);
}
Now, For my CGridView i am using a model->search()of the Importedbooks model as my dataProvider, From here is where i get stuck.
CGridView
$data = $model->search();
$data->setPagination(array('pageSize'=>'5'));
$data->criteria->addCondition('active = "yes"');
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$data
,'filter'=>$model
,'pager'=>array('header'=>'')
,'columns'=>array(
'id',
'bookYear',
'bookTitle',
'DISPLAY VALUE FROM OTHER model HERE'
)
)
);
DataProvider of the Imported books model, i'm using this as my data provider for the grid
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('bookID',$this->bookID);
$criteria->compare('countryName',$this->countryName,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
The relation works because i can use below code in my controller to get a field(countryName) from the other model
$model = Importedbooks::model()->with('CountryOfImportObj')->findbyPK(3);
print_r($model->CountryOfImportObj[0]->countryName);
Such as Importedbooks have many CountryOfImport, in one row you must show or all country names or concreet names depending on ID or countryName or some other attribute.
You can pass anonymous function as value:
'columns' => array(
'id',
'bookYear',
'bookTitle',
array(
'header' => 'Countries',
'type' => 'raw',
// if you have defined counrtyName attribute in 'Importedbooks' model, if not you can remove this row
// also CGridView 'uses' attribute 'name' for filtering or sorting
'name' => 'countryName',
'value' => function($data, $row) { //$data is item of DataProvider, $row is number of row (starts from 0)
$countries = CHtml::listData((array)$data->CountryOfImportObj, 'id', 'countryName');
return implode(', ', $countries);
}
)
)
If you want to filter or sort by external attributes too, you must "declare them"
Thanks!
I have a problem regarding the use of CDbCriteria in a controller index action. I have 2 classes: event and attendee.
the class event has many attendee, and i want my event index action to render only the list of events of which the current loggedin user is an attendee...
$criteria = new CDbCriteria(array(
'order'=>'event_date desc',
'with' => array('attendees'=>array('alias'=>'attend')),
'condition'=>'attend.uid = ' . Yii::app()->user->id,
));
$dataProviderAtt=new CActiveDataProvider('Event',
array(
'criteria' => $criteria,
)
);
$this->render('index',array(
'dataProvider'=>$dataProviderAtt,
));
this does not work in DB with the message:
CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'user'
my relations in attendee class are set like this:
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'user' => array(self::BELONGS_TO, 'YumProfile', 'uid', 'alias'=>'user'),
);
}
I tried to change the defaultscope in attendee model and define multiple aliases:
public function defaultScope()
{
static $counter = 0;
return array(
'with' => array('user'=>array('alias'=>'user'.($counter++))),
//'with' => 'user',
'order' => 'score DESC',
);
}
but it does not seem to fix the issue and I then have more errors. Is my criteria correctly set?
Thx guys for your help
you are looking for
'on' => 'attend.uid = ' . Yii::app()->user->id,
as in your relation to the user
function relations()
{
return array(
'user' => array(
self::BELONGS_TO,
'attendees',
'',
'on' => 'attendees.uid = ' . Yii::app()->user->id,
),
);
}
Guardian model:(relation)
'studentsGuardians' => array(self::HAS_MANY, 'StudentsGuardian', 'guardian_id'),
Student model relation:
'studentsGuardians' => array(self::HAS_MANY, 'StudentsGuardian', 'student_id'),
Students Guardian model relation:
'guardian' => array(self::BELONGS_TO, 'Guardian', 'guardian_id'),
'student' => array(self::BELONGS_TO, 'Student', 'student_id'),
Now in controller i want to select those students whose guardian_id=id but my code select all records without filtering. my code is
public function actionAssignGuardian($id)
{
$dataProvider = new CActiveDataProvider('Student',
array(
'criteria' => array(
'with'=>array('studentsGuardians',
array('criteria'=>
array('with'=>array('guardian','condition'=>' guardian_id=:id',
'params'=>array('id'=>$id))))),
),
));
$this->renderPartial('Pages/_assignGuardian', array(
'dataProvider' => $dataProvider,
'id'=>$id,
));
}
Kindly point me to correct way that how could i select those students whose guardian_id= given id in function. I am new to yii.
Thanks.
Add this line into Student model (below previous relation line studentsGuardians)
'guardians' => array(self::HAS_MANY, 'Guardian', array('guardian_id'=>'guardian_id'),'through'=>'studentsGuardians'),
Then you can do query like this
$dataProvider = new CActiveDataProvider('Student',
array(
'criteria' => array(
'with'=>array(
'guardians' =>array(
'condition'=>' guardian_id=:id',
'params'=>array('id'=>$id)
)))
));
(You should also dump $id to make sure that it is valid value)
Hi I have a database where i use a link table to link products and categories.
The relationships look like this:
Product ProductCategories Category
Id Id Id
Name ProductId Name
CategoryId
So the productCategory table links Products to Categories
My problem is when im trying to find all Products under the category with the Id of 1
I use this code but it doesnt seem to be working:
$models = Products::model()->with('productcategories')->findByPk(1);
This is the Products Relationships:
public function relations()
{
return array(
'productcategories' => array(self::HAS_MANY, 'Productcategories', 'ProductId'),
);
}
public function relations()
{
return array(
'productcategories' => array(self::HAS_MANY, 'Productcategories', 'ProductId'),
'Categories' => array(self::HAS_MANY, 'Category', '',
'through'=>'productcategories',
'on' => 'Categories.Id = productcategories.CategoryId',
),
);
}
// Get all Product with a Category with id = 1
$models = Products::model()->with('Categories')->findAll('Categories.Id = 1');
I have a strange problem with my yii application. I have two tables in my database Players - id, name, team_id and Teams - id, name. I can create new players but when I want to see player's profile there is an error -"Trying to get property of non-object" at this line:
'value'=>$model->team->NAME,
The most strange problem is that when I test url for players with Ids 1 and 2 everything is okay and I see the correct information, but for other ids I have this problem. Here is part of my code:
view.php
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'ID',
'NAME',
'TEAM_ID',
array(
'label'=>'Отбор',
'type'=>'text',
'value'=>$model->team->NAME,
),
),
)); ?>
Players.php
public function relations()
return array(
'team' => array(self::BELONGS_TO, 'TEAMS', 'ID'),
);
}
Teams.php
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'player' => array(self::HAS_MANY, 'PLAYERS', 'ID'),
);
}
PlayersController.php
public function actionView($id)
{
$teams = new CActiveDataProvider('Teams');
$players = new CActiveDataProvider('Players');
$this->render('view', array(
'model'=>$this->loadModel($id),
));
}
Seems like you need to fix bug with relations in Players model:
public function relations()
return array(
'team' => array(self::BELONGS_TO, 'TEAMS', 'TEAM_ID'), // TEAM_ID instead of ID
);
}