Home  >  Article  >  PHP Framework  >  Model type conversion problem in tp5.0

Model type conversion problem in tp5.0

藏色散人
藏色散人forward
2019-08-19 14:22:382662browse

Model type conversion problem in tp5.0

Model type conversion problem of tp5.0

When using data ()->save () When, the second parameter of the data function must be set to true in order to achieve type conversion

class User extends Model 
{
    protected $type = [
        'status'    =>  'integer',
        'score'     =>  'float',
        'birthday'  =>  'datetime',
        'info'      =>  'array',
    ];
}

1. Type conversion is possible

$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. Type conversion is not possible

$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. Capable of type conversion

$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;
    }
.......

Type conversion can only be performed through the setAttr function

This article comes from the ThinkPHP framework technical article column:http://www.php.cn/phpkj/ thinkphp/

The above is the detailed content of Model type conversion problem in tp5.0. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete