Simon
Simon

Reputation: 189

Yii Framework - Storing field from a different table into a model

I need some help with the Yii 2.x framework.

I have 2 tables, stuff and table, each with their own models, Stuff and Table.

stuff and table share a key. stuff contains table_id which links to id in table.

The stuff controller contains the following code to retrieve all fields from stuff and the age field from table:

$model = Stuff::find ()
                ->select (['`stuff`.*', '`table`.`age`'])
                ->leftJoin ('table', '`stuff`.`table_id`=`table`.`id`', [])
                ->where (['table_id' => $id])
                ->one ()

Once executed, $model contains everything from the stuff table, but does not contain the age field, even though the generated SQL does retrieve it. I have found that adding public $age; into the Stuff model does store the age field, however this seems like a hack and feels dirty.

So my question is, is it possible to get the $model variable to store fields from a referenced table without altering the original model? If that's not possible, is there a more correct way of doing things than what I have already done?

Thanks!

Upvotes: 1

Views: 117

Answers (2)

Mohan Rex
Mohan Rex

Reputation: 1674

Define relation in the stuff model like this

public function getTable()
{
    return $this->hasOne(Table::className(), ['id' => 'table_id']);
}

and then you can access it via referenced object like

$model->table->age

Upvotes: 1

hamed
hamed

Reputation: 8033

You can access related model fields in the object oriented fashion, something like this:

$model->table->age

In the above expression, table is relation name in the Stuff model.

Upvotes: 1

Related Questions