[英]Yii2 - How to get field value from relation
I have a table which has different types of text data from different sources, identified by type, lang, sourceId and stored in field text
.我有一个表,其中包含来自不同来源的不同类型的文本数据,由类型、语言、源 ID 标识并存储在字段text
。 Is there anyway to return by active record relation not object of table but only value of field text
in oher words scalar query via relation?无论如何,是否可以通过活动记录关系返回而不是表的对象,而是仅通过关系返回其他单词标量查询中的字段text
值?
Example: For now I have:示例:现在我有:
$modelName->RelationName->text) //field name storing expexted data, returns string.
Desired way is:想要的方式是:
$modelName->RelationName//text field value returned only.
Yes But using lazy loading
approach :是但使用lazy loading
方法:
Update Your Relation as将您的关系更新为
public function getRelationName(){
//Related model Class Name
//related column name as select
return $this->hasOne(RelationClass::className() ,['id' => 'id'])->select('name')->scalar();
}
then get relation value as : -然后得到关系值: -
$modelName->relationName//text field value returned only.
Extend your model with one or more getter for retrive the value you need using a relation eg:使用一个或多个 getter 扩展您的模型,以使用关系检索您需要的值,例如:
In the model you need retrive the related data you can build a funtion for define the raltion (in this case an hasOne)在您需要检索相关数据的模型中,您可以构建一个函数来定义关系(在本例中为 hasOne)
*/
public function getRelationName()
{
return $this->hasOne(ModelOfTheRelation::className(), ['column1' => 'column1', 'EvColumn2' => 'Evcolumn2']);
}
Then you can use getter function for the data然后你可以对数据使用getter函数
/* Getter f */
public function getRelatioName_field()
{
return $this->relationName->field;
}
In view you can easy obtain the data using鉴于您可以使用以下方法轻松获取数据
echo $model->relationName_field
or in gridview (dataprovider)
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'relationName_field',
this link could be useful http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/此链接可能很有用http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/
编辑:删除旧的和错误的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.