AR - Join

I try to get data from a JOINed table:

$crit = new CDbCriteria();

$crit->condition = ‘page > :page’;

$crit->params = array(’:page’=>0);

$crit->limit = 20;

$crit->join = ‘LEFT JOIN table_2 ON table_2.id=page’;

$rows=$ar->findAll($crit);

Ok, that works. In table_2 I have a colum called ‘title’

I access all data in a foreach loop

foreach ($rows as $row)

That works too.

But the following code makes an exception

echo $row->title;

because (imho) this is table_2

But how can I access columns of the JOINed table ?

Thx 4 help

Scryii

You can print the $row and you will see where your data is, I think you can access this title throug something like this $row->table2->title

But try to print $row and see where the data is

Thx for help.

Did you mean the following code ?

print $row;

That doesn’t work.

Also the access via $row->table_2->title doesn’n work.

I still get the exception:

Property "MyApplication.table_2" is not defined.

try to use with() method for table joinings.

Read this article http://www.yiiframew…en/database.arr and join the tables by setting relational property

You can check generated query in yii log and you will see what she is getting

That looks good.

I’m sure that is the right way, I will check it.

On the other site it looks more complex.

I have only one AR for the table_1.

To follow your idea, I have to generate an AR for table_2 too,

because relations are only possible btw. AR.

The using of the join property in an AR is very simple and generates the

right table (in my opinion => I tested in phpMyAdmin).

Is there really not a simple way to access the JOINed columns ?

You can add ‘title’ property to your model:




class MyModel extends CActiveRecord

{

    public $title;


    // ...

}



But Yii can do all job for you, if you’ll create AR class for table_2 and add a relation to your model.

Ok, thanks, let us do this step by step:

  1. I Generate the model class for table_2 using Gii => ok

  2. I added to the model class of table_1 (function relation) the line:

‘name’=>array(self::BELONGS_TO, ‘Table2Class’, ‘id’),

=> ok

  1. Then I changed the call:

$rows=$ar->findAll($crit);

to

$rows=$ar->with(‘name’)->findAll($crit);

=> ok

  1. And now the question: How I can access the ‘title’ colum of table_2 ?

echo $row->title;

doesn’t work (exception)

scryii

P.S.: When I copy the logged SQL Statement to myPHP admin => the JOINed table looks perfect. It’s only the last step - the access to the colum.

What’s about $row->name->title?

Thanx.

That works.

B)