Scryii
(Dirk Gollnick)
1
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
ignis55
(I Nedzinskas)
2
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
Scryii
(Dirk Gollnick)
3
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.
ignis55
(I Nedzinskas)
4
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
Scryii
(Dirk Gollnick)
5
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 ?
andy_s
(Arekandrei)
6
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.
Scryii
(Dirk Gollnick)
7
Ok, thanks, let us do this step by step:
-
I Generate the model class for table_2 using Gii => ok
-
I added to the model class of table_1 (function relation) the line:
‘name’=>array(self::BELONGS_TO, ‘Table2Class’, ‘id’),
=> ok
- Then I changed the call:
$rows=$ar->findAll($crit);
to
$rows=$ar->with(‘name’)->findAll($crit);
=> ok
- 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.
andy_s
(Arekandrei)
8
What’s about $row->name->title?