TP5使用模型添加数据

先引入模型类

use app\index\modle\User;

create 方法, save 方法, saveAll() 方法

 1. create 方法. 直接使用 model的 create 方法

$res = User::create([
    'username' => 'imooc',
    'password' => md5('imooc'),
    'email'    => '[email protected]',
    'num'      => 100,
]);
dump($res);

create方法需要注意, 如果字段不存在, 则插入错误. 如果将第二个参数设置为 true, 则可以正常插入.

$res = User::create([
    'username' => 'imooc',
    'password' => md5('imooc'),
    'email'    => '[email protected]',
    'num'      => 100,
    'demo'     => 123,
], true);
dump($res->id);

还需要注意, 字段有很多, 如果我们想设置, 只允许2个字段可以插入, 则将第二个参数, 修改为 数组,里面的值, 就是只允许加入的值.

$res = User::create([
    'username' => 'imooc',
    'password' => md5('imooc'),
    'email'    => '[email protected]',
    'num'      => 100,
    'demo'     => 123,
], ['username', 'email']);
dump($res->id);

2. save方法, 使用前需要先实例化model类.

$userModel           = new User;
$userModel->username = '1771258';
$userModel->email    = '[email protected]';
$userModel->save();

//自增id
dump($userModel->id);

save方法还有一种比较简单的方式, 要实例化, 返回的是 添加成功的条数.

$userModel = new User;
$res = $userModel->save([
    'username' => 'imooc1',
    'password' => md5('imooc1'),
]);

这时候需要注意, 如果加入一个数据库不存在的字段, 数据库会报错, 所以要加入一个参数.

$userModel = new User;
$res       = $userModel
    ->allowField(true)
    ->save([
        'username' => 'imooc1',
        'password' => md5('imooc1'),
        'demo'     => 123
    ]);

如果 allowField 的参数是一个数组, 则表示, 只允许数组中的值 添加到数据库.

3. saveAll() 方法, 一次性添加多条数据

//添加多条数据
$userModel = new User;
$res       = $userModel->saveAll([
    ['email' => '[email protected]'],
    ['email' => '[email protected]']

]);
foreach ($res as $val) {
    dump($val->toArray());
    //自增id
    dump($val->id);
}
发布了88 篇原创文章 · 获赞 6 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/codipy/article/details/92805298