laravel增删改查
xuexi 2023-07-04 10:31:24 发表在:PHP 查看数:1057

基本用法

查询一条:

$code = 模型::where('code',$request->code)->first();

查询其中一个字段数据

DB::table('users')->select('name', 'email')->get();
$email = DB::table('users')->pluck('email');
$id = DB::table('users')->where('name', 'John')->value('id');
 $users = DB::table('users')->get();

以上示例是从users表中获取所有用户的记录。如果要获取单条记录,可以使用以下代码:

 $user = DB::table('users')->where('name', 'John')->first();

以上代码将从users表中获取第一条name为John的记录

a. where条件查询

 $users = DB::table('users')->where('name', '=', 'John')->get();

以上示例从users表中查询name等于'John'的记录。可以通过第二个参数来指定条件类型,如'>'、'<'、'>='、'<='等。

b. orWhere条件查询

 $users = DB::table('users')->where('name', '=', 'John')->orWhere('name', '=', 'Mary')->get();

以上示例是从users表中查询name等于'John'或'name'等于'Mary'的记录。

c. 多个Where条件查询

 $users = DB::table('users')->where([
    ['status', '=', '1'],
    ['name', '<>', 'John']
])->get();

以上示例是从users表中查询status等于1而且name不等于John的记录。

d. whereBetween条件查询

$users = DB::table('users')->whereBetween('votes', [1, 100])->get();

以上示例是从users表中查询votes在1-100之间的记录。

e. whereIn条件查询

$users = DB::table('users')->whereIn('id', [1, 2, 3])->get();

以上示例是从users表中查询id在1、2、3中的记录。

f. orderBy排序查询

$users = DB::table('users')->orderBy('name', 'desc')->get();

以上示例是按照name倒序排列查询users表中的记录。

DB类的插入、更新、删除操作

Laravel DB类不仅支持查询操作,还支持插入、更新和删除操作。以下是一些示例:

a. 数据插入

DB::table('users')->insert([
    'email' => 'john@example.com',
    'name' => 'John Doe'
]);

以上示例向users表中插入一条email为john@example.com,name为John Doe的记录。

b. 数据更新

DB::table('users')->where('id', 1)->update(['votes' => 1]);

以上示例更新了id为1的用户的投票数为1。

c. 数据删除

DB::table('users')->where('votes', '<', 100)->delete();

以上示例删除votes小于100的所有用户。

DB类的事务操作

数据操作过程中,很可能会发生意外,比如在插入数据时出现错误。这时候就需要回滚事务,以确保数据的完整性。Laravel DB类支持事务操作。以下是一个示例:

DB::transaction(function () {
    DB::table('users')->update(['votes' => 1]);
    DB::table('posts')->delete();
});

以上示例是一个简单的事务,它更新users表中的所有用户的投票数为1,并删除posts表中的所有记录。如果在事务过程中发生错误,则会自动回滚并保持数据的完整性。

DB类的连接和表名

在大多数情况下,Laravel DB类会自动连接默认的数据库和表,但是在某些情况下,我们需要手动指定连接和表名。以下是一个示例:

$users = DB::connection('connection-1')->table('users')->get();

以上示例是在第一个连接中显示获取users表中的所有数据。我们可以在config/database.php文件中配置多个连接信息。

结论

通过Laravel DB类,我们可以方便地进行数据库操作。从简单的数据查询到复杂的事务操作,Laravel DB类都提供了相应的方法和语法。在实际开发中,我们可以根据需要结合使用查询构造器、事务和连接,以实现灵活高效的数据操作。

最近访问时间:2025-05-01 05:49:36
知识库:340条鸣谢:TAY  备案号:蜀ICP备2024090044号