从零开始系列-Laravel编写api服务接口:7.数据库添加和更新(未完待续)

简介

添加和更新是比较常用的操作,下面总结一下

1.添加

 // 先填充模型
 $user = new User([
            'name' => 'test123',
            'email' => 'test@test.com'.random_int(10,99),
            'email_verified_at' => '2021-1-5',
            'password' => bcrypt('123456'),
            'remember_token' => 'ABABAB',
            'status' => 0,
        ]);
 // 或者 
 $user = new User();
 $user->fill([
            'name' => 'test123',
            'email' => 'test@test.com'.random_int(10,99),
            'email_verified_at' => '2021-1-5',
            'password' => bcrypt('123456'),
            'remember_token' => 'ABABAB',
            'status' => 0,
        ]);

// 调用 save() 保存数据
$bool = $user->save(); // 返回成功或者失败
// 此时$user模型已经被填充了数据并且已保存到数据库
$user = User::create([
            'name' => 'test123',
            'email' => 'test@test.com'.random_int(10,99),
            'email_verified_at' => '2021-1-5',
            'password' => bcrypt('123456'),
            'remember_token' => 'ABABAB',
            'status' => 0,
        ]);

2.修改

$bool = User::find(15)->update([
            'name' => 'test1234',
        ]);
//或
$user = User::find(15);
$user->name = 'test1234';
$user->save();

3.查找返回或添加

// 不存在则添加
$user = User::firstOrCreate(['id'=>15],
        [
        'name' => 'test123',
        'email' => 'test@test.com'.random_int(10,99),
        'email_verified_at' => '2021-1-5',
        'password' => bcrypt('123456'),
        'remember_token' => 'ABABAB',
        'status' => 0,
    ]);
    dd($user);

4.查找修改或添加

// 存在记录则修改,否则添加
$user = User::updateOrCreate(['id'=>15],
            [
            'name' => 'test123',
            'email' => 'test@test.com'.random_int(10,99),
            'email_verified_at' => '2021-1-5',
            'password' => bcrypt('123456'),
            'remember_token' => 'ABABAB',
            'status' => 0,
        ]);

5.批量插入

6.批量更新

本作品采用《CC 协议》,转载必须注明作者和本文链接
编程两年半,喜欢ctrl(唱、跳、rap、篮球)
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!