laravel 查询构造器


1、获取所有值
DB::table('users')->get()

2、获取一条数据
DB::table('users')->where('name','alex')->first();

3、获取某个字段
DB::table('users')->where('name','alex')->value('email');

4、获取一列值
DB::table('users')->plunk('name');
你也可以在返回的数组中指定自定义的键值字段:
DB::table('users')->plunk('name','age');
返回值会是:[ 'age1'=>'name1','age2'=>'name2'... ]

5、结果分块
chunk(),先不看

6、聚合
DB::table('users')->count();
DB::table('orders')->max('price');
DB::table('orders')->where('finalized', 1)->avg('price');

7、selects
指定返回字段
DB::table('users')->select('name', 'email as user_email')->get();
distinct 返回不重复结果
DB::table('users')->distinct()->get();
如果你已有一个查询构造器实例,并且希望在现有的 select 子句中加入一个字段,则可以使用 addSelect 方法:
$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();

8、原始表达式
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();

9、Joins
不会,后期补充

10、Unions(合并)
$first = DB::table('users')
->whereNull('first_name');

$users = DB::table('users')
->whereNull('last_name')
->union($first)
->get();

11、where

where('votes', '>=', 100) where('name', 'like', 'T%')
或数组
where([
['status', '=', '1'],
['subscribed', '<>', '1'],
])

其他还有orWhere,whereBetween,whereNotBetween,WhereIn,whereNotIn,whereNull 与 whereNotNull,whereDate / whereMonth / whereDay / whereYear,

whereColumn方法用来检测两个列的数据是否一致
whereColumn('first_name', 'last_name')
还可以使用运算符
whereColumn('updated_at', '>', 'created_at')
可以接收数组参数
whereColumn([
['first_name', '=', 'last_name'],
['updated_at', '>', 'created_at']
])
where还有很多用法,用到时可以详细研究

12、Ordering, Grouping, Limit 及 Offset
用到时查询

13、条件语句
when() 之后再补充

增 insert

DB::table('users')->insert(
['email' => 'john@example.com', 'votes' => 0]
);
若数据表存在自增 id,则可以使用 insertGetId 方法来插入记录并获取其 ID:
$id = DB::table('users')->insertGetId(
['email' => 'john@example.com', 'votes' => 0]
);

改 update

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

自增或自减
DB::table('users')->increment('votes');
DB::table('users')->increment('votes', 5);
DB::table('users')->decrement('votes');
DB::table('users')->decrement('votes', 5);

您还可以指定要操作中更新其它字段:
DB::table('users')->increment('votes', 1, ['name' => 'John']);

删 delete

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

如果你需要清空表,你可以使用 truncate 方法,这将删除所有行,并重置自动递增 ID 为零:
DB::table('users')->truncate();

eloquent 模型更好用应该,还没看到,后期补充

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • laravel数据库使用简易说明 首先可以使用查询构造器和EloquentORM两种方式 目前支持的数据库类型有:...
    hankviv阅读 771评论 0 0
  • 转载,觉得这篇写 SQLAlchemy Core,写得非常不错。不过后续他没写SQLAlchemy ORM... ...
    非梦nj阅读 5,490评论 1 14
  • 配置 修改config/database.php在connection数组中添加mongodb的配置信息,如下 '...
    jooohnny阅读 8,474评论 3 8
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,973评论 19 139
  • MySQL 数据库常用命令 1、MySQL常用命令 create database name; 创建数据库 use...
    55lover阅读 4,830评论 1 57