简体   繁体   English

Yii Framework-将字段从其他表存储到模型中

[英]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张桌子, stufftable ,每个都有自己的模型, StuffTable

stuff and table share a key. stufftable共用一个钥匙。 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. 在上面的表达式中, tableStuff模型中的关系名称。

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.

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