简体   繁体   中英

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 . 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?

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 :

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:

In the model you need retrive the related data you can build a funtion for define the raltion (in this case an hasOne)

 */
public function getRelationName()
{
    return $this->hasOne(ModelOfTheRelation::className(), ['column1' => 'column1', 'EvColumn2' => 'Evcolumn2']);
}

Then you can use getter function for the data

/* 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/

编辑:删除旧的和错误的答案。

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