tp5.0 的模型类型转换问题

当用data()->save()的时候,data函数的第二个参数必须设为true的时候才能 实现类型转换

class User extends Model 
{
    protected $type = [
        'status'    =>  'integer',
        'score'     =>  'float',
        'birthday'  =>  'datetime',
        'info'      =>  'array',
    ];
}
  1. 能类型转换
    $user = new User;
    $user->status = '1';
    $user->score = '90.50';
    $user->birthday = '2015/5/1';
    $user->info = ['a'=>1,'b'=>2];
    $user->save();
    var_dump($user->status); // int 1
    var_dump($user->score); // float 90.5;
    var_dump($user->birthday); // string '2015-05-01 00:00:00'
    var_dump($user->info);// array (size=2) 'a' => int 1  'b' => int 2
  2. 不能类型转换
    $user = new User;
    $insert ['status'] = '1';
    $insert ['score'] = '90.50';
    $insert ['birthday'] = '2015/5/1';
    $insert ['info'] = ['a'=>1,'b'=>2];
    $user->data($insert)->save();
    var_dump($user->status); // string '1';
    var_dump($user->score); // string '90.5';
    var_dump($user->birthday); // string '2015/5/1'
    var_dump($user->info);// array (size=2) 'a' => int 1  'b' => int 2
  3. 能类型转换
    $user->data($insert, true)->save();
Model.php
......
  public function data($data, $value = null)
    {
        if (is_string($data)) {
            $this->data[$data] = $value;
        } else {
            // 清空数据
            $this->data = [];
            if (is_object($data)) {
                $data = get_object_vars($data);
            }
            if (true === $value) {
                // 数据对象赋值
                foreach ($data as $key => $value) {
                    $this->setAttr($key, $value, $data);
                }
            } else {
                $this->data = $data;
            }
        }
        return $this;
    }
.......

只有经过setAttr函数才会进行类型转换

如果你不想一死就被忘记,要么写点值得读的东西,要么做点值得写的事情

讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!