yii2在运行时添加属性

时间:2017-09-25 11:43:29

标签: yii properties

尝试为我的CRM系统添加属性到我的AR模型。

public function getCustomFields($key = null)
{
    if (static::$customFields === null)
    {
        $fields = (new Query)->from('client_fields')->indexBy('key')->all(static::$conn);

        if ($columns = static::$conn->getSchema()->getTableSchema('client_profiles')->getColumnNames())
        {
            foreach ($columns as $column)
            {
                if (isset($fields[$column]))
                {
                    static::$customFields[$column]['name'] = $fields[$column]['name'];
                    static::$customFields[$column]['settings'] = @json_decode($fields[$column]['settings'], true);
                }

                if( ! isset($this->{$column}))
                {
                    $this->{$column} = null;
                }
            }
        }

        static::$customFields = static::$customFields ?: [];
    }

    return $key ? (isset(static::$customFields[$key]) ? static::$customFields[$key] : null) : static::$customFields;
}

结果如下:

Setting unknown property: common\modules\crm\models\CrmClient::user_id

等待解决此问题的最佳解决方案......

1 个答案:

答案 0 :(得分:1)

首先在模型中定义所有属性,当您创建模型Gii时,您将看到属性定义。

e.g

/**
 * This is the model class for table "user_activity".
 *
 * @property integer $ua_id
 * @property integer $user_id
 * @property string $filename
 * @property integer $created_at
 *
 * @property User $user
 */