TP5使用模型添加数据

先引入模型类

use app\index\modle\User;

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

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

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

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

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

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

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

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

$userModel           = new User;
$userModel->username = '1771258';
$userModel->email    = '1771258@qq.com';
$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' => '12222@qq.com'],
    ['email' => '177@qq.com']

]);
foreach ($res as $val) {
    dump($val->toArray());
    //自增id
    dump($val->id);
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值