laravel mysql sum,Laravel 数据库操作
mysql
DB
运行原始语句
select 查找
// 参数绑定
$users = DB::select('select * from users where active = ?', [1]);
// 命名绑定
$results = DB::select('select * from users where id = :id', ['id' => 1]);
insert 插入
// 返回受影响的行数
DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
update 更新
// 返回受影响的行数
$affected = DB::update('update users set votes = 100 where name = ?', ['John']);
delect 删除
// 返回受影响的行数
$deleted = DB::delete('delete from users');
运行一般声明
不返回任何参数
DB::statement('drop table users');
数据库事务
// 闭包事务
DB::transaction(function () {
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
});
// 手动事务
// 开启事务
DB::beginTransaction();
// 事务还原
DB::rollBack();
// 事务提交
DB::commit();
使用多数据库连接
$users = DB::connection('foo')->select(...);
查询构造器
查询 user 表所有记录
$users = DB::table('users')->get();
查询单条记录
$user = DB::table('users')->where('name', 'John')->first();
$email = DB::table('users')->where('name', 'John')->value('email');
将结果切块
DB::table('users')->chunk(1, function($users) {
foreach ($users as $user) {
if($user->id === 1){
echo $user->name;
return false;
}
}
});
获取某个字段值列表
// 返回包含单个字段值的数组
$nameArr = DB::table('users')->lists('email');
// 返回的数组中指定自定义的键值字段
$users = DB::table('users')->lists('email','name');
聚合操作(count、max、min、avg、以及 sum)
$users = DB::table('users')->count();
$price = DB::table('orders')->where('finalized', 1)->max('price');
取出数据表中的部分字段
$users = DB::table('users')->select('name', 'email as user_email')->get();
去除重复的值
$time = DB::table('users')->select('created_at')->distinct()->get();
在原有查询构造器实例的select子句中增加一个字段
$query = DB::table('users')->select('name');
$users = $query->addSelect('email')->get();
原始表达式
$users = DB::table('users')->select(DB::raw('count(*) as user_count, status'))->where('status', '<>', 1)->groupBy('status')->get();
Inner Join 内链接
$users = DB::table('users')->join('tasks', 'users.id', '=', 'tasks.user_id')->select('users.*', 'tasks.name as taskname')->get();
Left Join 外链接
$users = DB::table('users')->leftJoin('tasks', 'users.id', '=', 'tasks.user_id')->select('users.*', 'tasks.name as tname')->where('users.name', 'jorly')->get();
高级的 Join 语法
$users = DB::table('users')->join('tasks', function ($join) {
$join->on('users.id', '=', 'tasks.user_id')->where('users.id', '=', 1);
})->get();
union 和 unionAll 联合查询
$first = DB::table('users')->where('id',1);
$users = DB::table('users')->where('id',2)->union($first)->get();
where 和 orWhere 查询
$users = DB::table('users')->where('votes', 100)->get();
$users = DB::table('users')->where('id', '=', 1)->orWhere('name', 'jorly')->get();
whereBetween 和 whereNotBetween 查询
$users = DB::table('users')->whereBetween('id', [2, 5])->get();
$users = DB::table('users')->whereNotBetween('id', [2, 5])->get();
whereIn 和 whereNotIn 查询
$users = DB::table('users')->whereIn('id', [2, 5])->get();
$users = DB::table('users')->whereNotIn('id', [2, 5])->get();
whereNull 和 whereNotNull 查询
$users = DB::table('users')->whereNull('updated_at')->get();
$users = DB::table('users')->whereNotNull('updated_at')->get();
where 分组查询
// select * from users where name = 'John' or (votes > 100 and title <> 'Admin')
DB::table('users')->where('name', '=', 'John') ->orWhere(function ($query) {
$query->where('votes', '>', 100)->where('title', '<>', 'Admin');
})->get();
orderBy 排序查询
$users = $users = DB::table('users')->orderBy('id', 'desc')->get();
groupBy、having 与 havingRaw
$users = DB::table('users')->groupBy('account_id')->having('account_id', '>', 100)->get();
$users = DB::table('orders')
->select('department', DB::raw('SUM(price) as total_sales'))
->groupBy('department')
->havingRaw('SUM(price) > 2500')
->get();
skip 与 take
$tasks = DB::table('tasks')->skip(1)->take(2)->get();
insert 插入数据
$tasks = DB::table('tasks')->insert([
['user_id' => 3, 'name' => 'demo1'],
['user_id' => 3, 'name' => 'demo2']
]);
插入记录并获取自增ID
$tasks = DB::table('tasks')->insertGetId(['user_id' => 4, 'name' => 'task1']);
update 更新数据
$result = DB::table('users')->where('id', 1)->update(['name' => 'ljh', 'email' => 'lijinhe@hudong.com']);
递增或递减
$result = DB::table('tasks')->where('id', 10)->increment('user_id', 5);
DB::table('users')->increment('votes', 1, ['name' => 'John']);
ORM
通过模型 Flight 查询 flights 表所有的记录
$flights = Flight::all();
模型中可使用任可查询构造器
$flights = Flight::where('active', 1)->orderBy('name', 'desc')->take(10)->get();
分块结果
Flight::chunk(200, function ($flights) {
foreach ($flights as $flight) {}
});
取回单个模型
$flight = Flight::find(1);
$flight = Flight::where('active', 1)->first();
「未找到」异常
$model = Flight::findOrFail(1);
$model = Flight::where('legs', '>', 100)->firstOrFail();
聚合函数
$count = Flight::where('active', 1)->count();
数据添加
$flight = new Flight;
$flight->name = $request->name;
$flight->save();
// 需要定义 $fillable 或 $guarded
$flight = Flight::create(['name' => 'Flight 10']);
// 当结果不存在时创建
$flight = Flight::firstOrCreate(['name' => 'Flight 10']);
// 当结果不存在时实例化
$flight = Flight::firstOrNew(['name' => 'Flight 10']);
$flight->save();
数据更新
$flight = Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();
Flight::where('active', 1)->where('destination', 'San Diego')->update(['delayed' => 1]);
删除数据
$flight = Flight::find(1);
$flight->delete();
// 通过主键来删除
Flight::destroy(1);
Flight::destroy([1, 2, 3]);
Flight::destroy(1, 2, 3);
// 通过查找来删除
$deletedRows = Flight::where('active', 0)->delete();
软删除(假删除)
// 需要使用 Illuminate\Database\Eloquent\SoftDeletes trait 并添加 deleted_at 字段到你的 $dates 属性上
// 需要被转换成日期的属性
protected $dates = ['deleted_at'];
mongodb
使用 composer 进行安装
$ composer require jenssegers/mongodb
在 config/app.php 注册 ServiceProvider 和 Facade(Laravel 5.5+ 无需手动注册)
'providers' => [
// ...
Jenssegers\Mongodb\MongodbServiceProvider::class,
],
'aliases' => [
// ...
'Moloquent' => Jenssegers\Mongodb\Eloquent\Model::class,
],
在 Eloquent 模型中使用
namespace App\Models;
use Jenssegers\Mongodb\Eloquent\Model;
use Jenssegers\Mongodb\Eloquent\HybridRelations;
class User extends Model
{
use HybridRelations;
// 连接的数据
protected $connection = 'mongodb';
// 与模型关联的集
protected $collection = 'user';
// 定义文档的主键
protected $primaryKey = '_id';
// 不可被批量赋值的属
protected $guarded = [];
// 附加到访问器模型的数
protected $appends = [];
// 应该被转换成原生类型的属
protected $casts = [
'data' => 'array'
];
}
关联模型使用示例:
$books = $user->books()->sortBy('title');
修改 config/database.php 默认连接方式
'default' => env('DB_CONNECTION', 'mongodb')
增加 mongodb 连接方式
'mongodb' => [
'driver' => 'mongodb',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', 27017),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
'options' => [
'database' => 'admin'
]
],
laravel mysql sum,Laravel 数据库操作相关推荐
- Node.js 连接 MySQL 并进行数据库操作 –node.js 开发指南
Node.js是一套用来编写高性能网络服务器的JavaScript工具包 通常在NodeJS开发中我们经常涉及到操作数据库,尤其是 MySQL ,作为应用最为广泛的开源数据库则成为我们的首选,本篇就来 ...
- laravel mysql sum查询并排行_必看!PHP常见面试题——MySQL篇(二)
接上期:<必看!PHP常见面试题--MySQL篇(一)> 11.MySQL的默认事务隔离级别是? 读未提交(RU): 一个事务还没提交时, 它做的变更就能被别的事务看到. 读提交(RC): ...
- mormot mysql,mORMot 数据库操作
mORMot 数据库操作 1 使用Access数据库, 引用SynCommons, SynDB,SynOleDb三个单元. var gProps: TSQLDBConnectionProperties ...
- emlog mysql文件,emlog数据库操作类
/** * 数据库操作类 * * @copyright (c) Emlog All Rights Reserved */ /** * MYSQL数据操方法封装类 */ class MySql { /* ...
- laravel mysql 配置,laravel5数据库配置及其注意事项
今天分享一个Laravel5数据库配置上的坑. Laravel5作为一套简洁.优雅的PHP Web开发框架(笑),唯一不足的一点就是中文手册或者说是资料比较少,虽然现在很多大神也开始普及这些东西,但是 ...
- nodec mysql_Node.js 连接 MySQL 并进行数据库操作 –node.js 开发指南
Node.js是一套用来编写高性能网络服务器的JavaScript工具包 通常在NodeJS开发中我们经常涉及到操作数据库,尤其是 MySQL ,作为应用最为广泛的开源数据库则成为我们的首选,本篇就来 ...
- Node.js 连接 MySQL 并进行数据库操作
Node.js是一套用来编写高性能网络服务器的JavaScript工具包 代码片段(6) [代码] 安装 node-mysql view source print? 1 $ npm install m ...
- unix mysql备份_数据库操作 备份篇 unix
show parameter kill session 查看 session SQL> select saddr,sid,serial#,paddr,username,status from v ...
- mysql pdo insert_PDO数据库操作类——插入数据的实现
mPHP核心框架使用PDO数据库抽象层往数据表中更新或插入数据,都是通过PDO的exec()方法,如果你熟悉Mysql数据库的sql语句,那么理解起来就更轻松了,你可以把它当作mysql的query( ...
最新文章
- MVC-前台调用后台action 传递upload file 参数问题
- linux编程取消wait函数,Linux编程基础之进程等待(wait()函数).pdf
- 我对创业和管理的一些看法
- sqlerror.java.1055,请问大佬,eclipse连接数据库出现这个错误怎么办
- vba mysql_VBA连接Mysql数据库
- CentOS 7.x 内核kernel版本升级实操
- Python崛金系列--4.python量化股票
- gdown配置代理下载Google drive文件
- php手机接收验证码,乐信揭秘php手机接收短信验证码实现编程案例
- 【开发心得】electron iohook集成使用方案
- 闭关修炼——five——Spring
- 香港机房BGP线路有什么用
- Git学习-Git时光机之版本回退(二)
- Html5工单系统,PESCMS Ticket(客服工单系统) V1.3.4 官方版
- 如何自己制作各种证件照和签证照片
- r语言java环境安装_【R语言入门】R语言环境搭建
- las文件matlab,基于Matlab的LAS格式数据解析与显示.pdf
- 美业多门店管理系统,智慧门店数字化方案
- 人物照片墙html 模板,用PS制作散落照片墙效果的人物照片
- 阿里java高级工程师面试100题
热门文章
- 计算机工程科学怎么翻译,汉英机器翻译中汉语篇章时间信息系统模型 - 计算机工程与科学.pdf...
- 【阿里云】解析与配置CNAME
- 转一首普希金的诗,给郁闷的日子煽煽情!
- 计算机硬盘对计算机速度的影响,实测加密软件BitLocker对硬盘性能有何影响
- IC验证培训——实战SV验证学习(lab5)
- 31 《象与骑象人:幸福的假设》 -豆瓣评分8.4
- 研发的首要目的是什么——一个容易被忽略的问题
- intel e1000 网卡 napi分析
- 电脑图片删除怎么找回?快试试这个方法!
- linux下freerdp编译,linux下安装freerdp连接windows远程桌面的好软件软件