简体   繁体   中英

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!

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM