tp5.0 的模型型別轉換問題

wowow發表於2019-08-09

當用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函式才會進行型別轉換

本作品採用《CC 協議》,轉載必須註明作者和本文連結

如果你不想一死就被忘記,要麼寫點值得讀的東西,要麼做點值得寫的事情

相關文章