如何将数据数组保存到数据库

时间:2019-05-08 09:23:00

标签: activerecord yii2

如何使用yii2活动记录将下面的数据数组保存到数据库中。

Array ( [0] => Array ( [0] => Array ( [UID] => RPS2019U002 [Name ] => Nishanth [Father] => mallesh [Mother] => Lakshmi [Occupation] => Govt Employee [Mobile] => 9856985689 [Email] => mallesh@gmail.com [Class] => UKG [dob] => 5/12/2016 [Route] => 1 [Addres] => Mysore [Remarks] => No ) [1] => Array ( [UID] => RPS2019U003 [Name ] => Nishanth [Father] => mallesh [Mother] => Lakshmi [Occupation] => Govt Employee [Mobile] => 9856985690 [Email] => mallesh@gmail.com [Class] => UKG [dob] => 5/13/2016 [Route] => 2 [Addres] => Mysore [Remarks] => No ) [2] => Array ( [UID] => RPS2019U004 [Name ] => Nishanth [Father] => mallesh [Mother] => Lakshmi [Occupation] => Govt Employee [Mobile] => 9856985691 [Email] => mallesh@gmail.com [Class] => UKG [dob] => 5/14/2016 [Route] => 3 [Addres] => Mysore [Remarks] => No ) ) [1] => Array ( ) [2] => Array ( ) )

1 个答案:

答案 0 :(得分:0)

最好的选择是使用json_encode / json_decode
您也可以使用serialize / unserialize
JSON 更具可移植性。它可以在任何编程语言中使用。 (更广泛的格式支持)
您可以使用getter和setter创建两个方法:(选择上述方法之一)
参见此 link
用于序列化:

serialize ([Array]); 
unserialize([Serialized value]);


模型迷 如果要在“验证规则”中检查阵列:

['yourField',function ($attribute, $params) {
    if(!is_array($this->valueYourField)){
         $this->addError('yourField','yourField not array!');
     }
}]

例如,如果您的数组只能是整数。使用allowArray

['yourField', 'in', 'range' => [1, 2, 3], 'allowArray' => true, 'message' => '{attribute} is invalid.']

您还可以在控制器中检查数组的内容,使用上述方法后,请在模型文件中使用Safe。(规则)

 ['yourField', 'safe'],

注意:请勿使用implode()。引起问题
还要选中此Extensionthis