[英]Yii Framework - Storing field from a different table into a model
I need some help with the Yii 2.x framework. 我需要有关Yii 2.x框架的帮助。
I have 2 tables, stuff
and table
, each with their own models, Stuff
and Table
. 我有2张桌子,
stuff
和table
,每个都有自己的模型, Stuff
和Table
。
stuff
and table
share a key. stuff
和table
共用一个钥匙。 stuff
contains table_id
which links to id
in table
. stuff
包含table_id
,它链接到table
id
。
The stuff
controller contains the following code to retrieve all fields from stuff
and the age
field from table
: stuff
控制器包含以下代码,用于从stuff
检索所有字段以及从table
检索age
字段:
$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. 执行后,
$model
包含stuff
表中的所有stuff
,但不包含age
字段,即使生成的SQL确实检索到了它。 I have found that adding public $age;
我发现增加了
public $age;
into the Stuff
model does store the age
field, however this seems like a hack and feels dirty. Stuff
模型中的数据确实存储了age
字段,但是这看起来像是骇客,而且感觉很脏。
So my question is, is it possible to get the $model
variable to store fields from a referenced table without altering the original model? 所以我的问题是,是否可以获取
$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. 在上面的表达式中,
table
是Stuff
模型中的关系名称。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.