<?php
class Client extends CActiveRecord
{
//...
public function relations()
{
return array(
'contacts'=>array(self::HAS_MANY,'Contact','idClient')
);
}
//...
And in ClientController…
<?php
//...
public function actionShow()
{
$client = $this->loadClient();
$criteria=new CDbCriteria;
$criteria->condition = 'idClient = '.$client->id;
$pages=new CPagination(Contact::model()->count($criteria)); // Just the contacts for that client
$pages->pageSize=self::PAGE_SIZE;
$pages->applyLimit($criteria);
$sort=new CSort('Contact');
$sort->applyOrder($criteria);
$contactList = $client->contacts; // Pay attention to this line
$this->render('show',array(
'client'=>$client,
'contactList'=>$contactList,
'pages'=>$pages,
'sort'=>$sort
));
}
I do that to have in mi show view the info about that client, and all the contacts of that client.
What I want is to paginate the contacts…
But neither pagination nor order works.(sorry about my very poor english)
But if I change that line (the one to pay attention) for that
<?php
//...
$contactList = Contact::model()->findAll($criteria); // I change the other line with than one....
$this->render('show',array(
'client'=>$client,
'contactList'=>$contactList,
'pages'=>$pages,
'sort'=>$sort
));
//...
2009/03/31 13:30:52 [trace] [system.db.CDbCommand] query with SQL: SELECT Client.id AS t0_c0, t3.id AS t3_c0, t3.idClient AS t3_c1, t3.lastname AS t3_c2, t3.name AS t3_c3, t3.phone AS t3_c4, t3.email AS t3_c5 FROM Client LEFT OUTER JOIN Contact t3 ON t3.idClient=Client.id WHERE Cliente.id=1
2009/03/31 13:30:52 [trace] [system.db.CDbCommand] query with SQL: SELECT COUNT(*) FROM Contact WHERE idClient = 1
2009/03/31 13:30:52 [trace] [system.db.CDbCommand] query with SQL: SELECT * FROM Contact WHERE idClient = 1 ORDER BY name DESC, lastname DESC, phone LIMIT 1
When I use $client->contacts;
2009/03/31 13:43:08 [trace] [system.db.CDbCommand] query with SQL: SQL: SELECT Client.id AS t0_c0, t3.id AS t3_c0, t3.idClient AS t3_c1, t3.lastname AS t3_c2, t3.name AS t3_c3, t3.phone AS t3_c4, t3.email AS t3_c5 FROM Client LEFT OUTER JOIN Contact t3 ON t3.idClient=Client.id WHERE Cliente.id=1
2009/03/31 13:43:08 [trace] [system.db.CDbCommand] query with SQL: SELECT COUNT(*) FROM Contact WHERE idClient = 1
$client->contacts; is not working because it has no chance to use the criteria at all (there is a ticket about specifying dynamic criteria for such lazy loading queries).
So you should use Contact::model() to query contacts with the criteria. Make sure you only fetch those contacts belonging to the current user.
I must use Contact::model()->findAll($criteria). Here $criteria the only thing that do is filter just the contacts of the current client. (Actullay I'm doing this and works perfect as I post above)
But if I use $client->contacts, it will not work… right?