Home> PHP Framework> ThinkPHP> body text

Model type conversion problem in tp5.0

藏色散人
Release: 2019-08-19 14:22:38
forward
2604 people have browsed it

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', ]; }
Copy after login

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
Copy after login

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
Copy after login

3. Capable of type conversion

$user->data($insert, true)->save();
Copy after login
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; } .......
Copy after login

Type conversion can only be performed through the setAttr function

This article comes from the ThinkPHP framework technical article column://m.sbmmt.com/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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!