0
votes

I have a relatively simple setup using Yii application but I'm struggling to access data across tables in the following scenario:

Two tables:

payments_info (id, data): where id is the primary auto increment key, model class name PaymentInfo

payments (id, payment_id, other_columns): here id is again a primary key and payment_id is foreign key pointing to one of the records in the payment_info table, model class name Payment

In the relations array inside the Payment model class I have the following:

'payment_id'=>array(self::BELONGS_TO, 'PaymentInfo', 'id'),

I haven't added anything in the PaymentInfo model's relations as technically it doesn't know anything about the other table.

I have a controller creating a CActiveDataProvider from the Payments model and showing all the records. In it, I'd like to have a field which would be showing the 'data' column from the PaymentInfo model but I have no idea how to get there.

In the cdbcriteria in the controller, used to create the data provider I tried using:

$criteria->with = array('payment_id');

And then in the view, inside the columns variable of the CGridView which displays the data provider I added:

array(
            'name'=>'payment_id',
            'visible'=>true,
            'value'=> $data->payment_id->data,
        ),

I also tried different combinations of adding ' or " around the $data variable but with no success so far. I manage to get the correct payment_id displayed but I can't figure out how to display the 'data' value from the other table. Any tips appreciated!

1

1 Answers

0
votes

you can use below method to Get Data From Another Relational Table in YII

Payment Model In Relation Function

public function relations()
    {
        return array(
            'pinfos'   => array(self::BELONGS_TO, 'PaymentInfo', 'payment_id'),
        );
    }

PaymentInfo Model In Relation Function

    public function relations()
    {
        return array(
            'payments'   => array(self::HAS_MANY, 'Payment', 'payment_id'),
        );
    }

And In zii.widgets.grid.CGridView put this

    <?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'post-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
    'pinfos.data',
     /* other fields goes here*/
    array(
        'class'=>'CButtonColumn',
    ),
),
)); ?>

No need to do anything else.