从零开始系列-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、篮球)
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

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