Laravel学习五:操作数据库

21 篇文章 0 订阅
7 篇文章 0 订阅

Laravel提供了DB facade(原始查找) 、查询构造器和Eloquent ORM三种操作数据库方式

1、运行原生sql

一旦配置好数据库连接后,便可以使用 DB facade 运行查询。 DB facade 为每种类型的查询提供了方法: select,update,insert,delete 和 statement。

①select查询

$users = DB::select('select * from users where active = ?', [1]);

A、参数绑定:传递给 select 方法的第一个参数就是一个原生的 SQL 查询,而第二个参数则是需要绑定到查询中的参数值。通常,这些值用于约束 where 语句。参数绑定用于防止 SQL 注入。

B、命名绑定:除了使用 ? 表示参数绑定外,你也可以使用命名绑定来执行一个查询:

$results = DB::select('select * from users where id = :id', ['id' => 1]);

②插入语句

参数绑定

DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);

③更新语句

$affected = DB::update('update users set votes = 100 where name = ?', ['John']);

返回受影响的行数

④删除语句

$deleted = DB::delete('delete from users');

返回受影响的行数

⑤运行普通语句

有些数据库语句不会有任何返回值。对于这些语句,你可以使用 DB Facade 的 statement 方法来运行:

DB::statement('drop table users');

2、查询构造器

Laravel 的查询构造器使用 PDO 参数绑定来保护您的应用程序免受 SQL 注入攻击。因此没有必要清理作为绑定传递的字符串。

①查询语句

a、从一个数据表中获取所有行

你可以 DB facade 上使用 table 方法来开始查询。该 table 方法为给定的表返回一个查询构造器实例,允许你在查询上链式调用更多的约束,最后使用 get 方法获取结果:

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

该 get 方法返回一个包含 Illuminate\Support\Collection 的结果,其中每个结果都是 PHP StdClass 对象的一个实例。你可以访问字段作为对象的属性来访问每列的值:

foreach ($users as $user) {
    echo $user->name;
}

B、从数据表中获取单行或单列:first()

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

如果你甚至不需要整行数据,则可以使用 value 方法从记录中获取单个值。该方法将直接返回该字段的值:

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

C、获取一列的值

如果你想获取包含单列值的集合,则可以使用 pluck 方法。在下面的例子中,我们将获取角色表中标题的集合:

$titles = DB::table('roles')->pluck('title');

你还可以在返回的集合中指定字段的自定义键值:

$roles = DB::table('roles')->pluck('title', 'name')

②聚合函数的方法

查询构造器还提供了各种聚合函数的方法,比如 count, max,min, avg,还有 sum。你可以在构造查询后调用任何方法:

$users = DB::table('users')->count();
$price = DB::table('orders')->max('price');

$price = DB::table('orders')
                ->where('finalized', 1)
                ->avg('price');

③判断记录是否存在

除了通过 count 方法可以确定查询条件的结果是否存在之外,还可以使用 exists 和 doesntExist 方法:

return DB::table('orders')->where('finalized', 1)->exists();
return DB::table('orders')->where('finalized', 1)->doesntExist();

④Where 语句

$users = DB::table('users')->where('votes', '=', 100)->get();

为了方便,如果你只是简单比较列值和给定数值是否相等,可以将数值直接作为 where 方法的第二个参数:

$users = DB::table('users')->where('votes', 100)->get();

orWhere 方法和 where 方法接收的参数一样:

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

whereBetween:方法验证字段值是否在给定的两个值之间:

whereNotBetween方法验证字段值是否在给定的两个值之外:

whereIn 方法验证字段的值必须存在指定的数组里,:

whereNotIn 方法验证字段的值必须不存在于指定的数组里:

whereNull 方法验证指定的字段必须是 NULL:

whereDate / whereMonth / whereDay / whereYear / whereTime

whereColumn 方法用于比较两个字段的值 是否相等

⑤orderBy排序操作

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

⑦groupBy 和 having 方法分组

$users = DB::table('users')
                ->groupBy('first_name', 'status')
                ->having('account_id', '>', 100)
                ->get();

⑧分页操作

DB::table('member')->limit('3')->offset(2)->get();
//limit:表示限制输出的条数
//offset:从什么地方开始。

⑨插入语句

查询构造器还提供了 insert 方法用于插入记录到数据库中。 insert 方法接收数组形式的字段名和字段值进行插入操作:

DB::table('users')->insert([
    ['email' => 'taylor@example.com', 'votes' => 0],
    ['email' => 'dayle@example.com', 'votes' => 0]
]);

⑩自增ID

如果数据表有自增 ID ,使用 insertGetId 方法来插入记录并返回 ID 值

$id = DB::table('users')->insertGetId(
    ['email' => 'john@example.com', 'votes' => 0]
);

⑪更新

数据修改可以使用update()、increment()和decrement()函数来实现,update表示修改整个记录的所有字段,increment()和decrement()修改数字数值(递增或者递减)

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

⑫删除

删除可以通过delete函数和truncate函数实现,delete表示删除记录,truncate表示清空整个数据表

DB::table('member')->where('id','1')->delete();
DB::table('member')->truncate();

3、Eloquent ORM操作数据库

public function orm(){
    //查询表的所有记录
    //$user = Admin::all();
    //dd($user);

    //查询某一条记录
    //$user = Admin::find(2);
    //dd($user);

    //findOrFail() 根据主键查找,如果没有找到就抛出异常
    //$user = Admin::findOrFail(1);
    //dd($user);

    //查询所有记录
    //$user = Admin::get();
    //dd($user);

    //增加条件查询
    //$user = Admin::where('uid','>=',4)->orderBy('uid','desc')->first();

    //分段查询
    //Admin::chunk(2,function($user){
        //var_dump($user);
    //});

    //聚合函数
    //获取记录的条数
    //$count = Admin::count();
    //dd($count);

    //获取最大值
    //$max = Admin::where('uid','>=',5)->max('age');

    //使用模型新增数据
    //$user = new Admin();
    //$user-> username = 'haha';
    //$bool = $user->save();
    //dd($bool);

    //获取时间
    //$user = Admin::find(1);
    //echo date('Y-m-d H:i:s',$user->create_at);

    //使用模型的Create方法新增数据
    //$user = Admin::create(['username'=>'meimei']);
    //dd($user);

    //以属性查找用户,如果没有则新增
    //$user = Admin::firstOrCreate(['username'=>'imooc']);
    //dd($user);

    //以属性查找用户,如果没有则新增,但不保存到数据库
    //$user = Admin::firstOrNew(['username'=>'imooc']);
    //dd($user);

    //通过模型更新数据
    //$user = Admin::find(1);
    //$user->username = 'jack';
    //$bool = $user->save();
    //dd($bool);

    //增加条件
    //$num = Admin::where('id','>','1')->update(['age'=>21]);
    //dd($num);

    //通过模型删除
    //$user = Admin::find(6);
    //$bool = $user->delete();
    //dd($bool);

    //通过主键删除
    //$num = Admin::destroy(6);
    //dd($num);

    //删除多条记录
    //$num = Admin::destroy(1,2,3);
    //$num = Admin::destroy([1,2,3]);
    //dd($num);

    //增加条件的删除操作
    //$num = Admin::where('uid','>','4')->delete();
    //dd($num);
}

参考文章:https://www.cnblogs.com/yxhblogs/p/5977965.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值