在模型中,我有两个值为数组的字段,implode
d在beforeSave()
上的模型中,并作为字符串保存到数据库中(这很好)。
现在,我需要知道,如何将这两个字段检索回afterFind()
上的数组,以便可以在表单中填充字段。
我应该注意,每个表单操作都是通过RESTful API完成的,而前端是在AngularJS中。
public $array_1 = [];
public $array_2 = [];
public function beforeSave($insert)
{
$this->array_1 = implode(',', $this->array_1);
$this->array_2 = implode(',', $this->array_2);
}
当我想按照相同的原则进行爆炸时,我得到的错误是explode
中的参数2期待字符串并且得到一个数组。我假设这是因为文件顶部的数组参数声明。
我是Yii2的新手,所以请保持温柔。 :)
答案 0 :(得分:1)
关于您的代码,我建议您做以下工作人员。
使用afterFind()和beforeSave()
//public $array_1 = []; ( those are redundant )
//public $array_2 = []; ( those are redundant )
public function afterFind()
{
$this->array_1 = explode(',', $this->array_1);
$this->array_2 = explode(',', $this->array_2);
}
有时我会这样做:
例如,而不是array_1,array_2我有一个"列",我希望它能够作为数组或原始值(来自DB)获取
public function getColumnArray()
{
return explode(',', $this->column)
}
public function setColumnArray($value)
{
$this->column = implode(',', $value);
}
所以当我写$ model-> columnArray时,它会给我$ model->列的数组值。如果我想要原始字符串,那么只需$ model->列
我希望这些是你需要的
答案 1 :(得分:0)
一个简单的方法是使用afterFind(在模型中)管理您的数据..所以每次检索模型时都可以执行需要的操作
public function afterFind()
{
$this->performYourManiplation();
}