【问题标题】:Get activerecord related field value when field is an expression in yii2yii2中字段为表达式时获取activerecord相关字段值
【发布时间】:2019-08-25 11:27:01
【问题描述】:

我正在扩展一个属性行为,它连接一些属性并将它们存储在另一个属性中。当属性连接或不在关系中时,代码工作正常。但是当我想使用“relatedtable.field”之类的属性时,没有办法告诉 AR 获取该相关字段的值:

这是我的 ConcatAttributesBehavior:

namespace app\components;

use yii\db\ActiveRecord;
use yii\base\Behavior;

class ConcatAttributesBehavior extends \yii\behaviors\AttributeBehavior
{
    public $source_attributes = [];
    public $separator = ", ";

    protected function getValue($event)
    {
    $ret = '';
    foreach( $this->source_attributes as $attribute ) {
        if( $ret != '' ) {
            $ret .= $this->separator;
        }
        $ret .= strval($this->owner->$attribute); (*) 
    }
    return $ret;
    }
}

当我将这些行为之一附加到我的模型时:

    public function behaviors()
    {
        return [ 
           'concat' => [
            'class' => \app\components\ConcatAttributesBehavior::class,
            'attributes' => [
                self::EVENT_BEFORE_INSERT => ['name'],
                self::EVENT_BEFORE_UPDATE => ['name'],
            ],
            'source_attributes' => [ 'person.name', 'school.name', 'date' ]
        ];
    }

我得到错误:

  [yii\base\UnknownPropertyException] Getting unknown property: app\models\Student::person.name

如果我查找person->name,则相同。

问题出在标有(*)的那一行

$ret .= strval($this->owner->$attribute); 

我已经尝试了所有这些变体:

$ret .= strval($this->owner->__get($attribute));
$ret .= strval($this->owner->getAtribute($attribute);

但它们都不起作用。

解决方案应包括设置多个关系,例如:

'person->school->address->country'

P.S 1) 如果我尝试,我的模型可以完美运行:

$student = Student::findOne(1);
echo $student->person->name;

P.S 2) 我在 AR __get 中缺少的代码与 BaseActiveRecord::getAttibuteHint 中的代码相似

【问题讨论】:

    标签: activerecord yii2


    【解决方案1】:

    你需要ArrayHelper::getValue():

    $ret .= strval(ArrayHelper::getValue($this->owner, $attribute));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多