laravel数据库

1.配置目录:
	config/database.php
2.读、写分离:
	'mysql' => [
		'read' => [
			'host' => '192.168.1.1'		// 多库读
			'host' => '192.168.1.2'
		],
		'write' => [
			'host' => '192.168.1.3'		// 单库写
		],
		'driver' => 'mysql',
		'database' => 'pxjy',
		...
	]
3.配置多个数据库链接:
	'mysql' => [						// 默认的数据库连接配置
		'host' => '192.168.1.1'
		'driver' => 'mysql',
		'database' => 'pxjy',
		...
	]
	'mysql_2' => [						// 自定义另外的数据库连接配置
		'host' => '192.168.1.2'
		'driver' => 'mysql',
		'database' => 'pxjy',
		...
	]
4.运行原生SQL查询:
	1>数据库的所有操作,使用 'DB' 命名的Facade。在控制器中使用:
		use DB;		// 1.引入依赖的DB类
		class UserController extends Controller{
		    public function index()
		    {
		        $users = DB::table('users')->get();		// 控制器中就可调用方法
		    }
		}
	2>原生SQL方法:
		select - 查询结果集,返回数组形式结果集。数组中每个结果都是一个PHP的StdClass对象
			$users = DB::select('select * from users where name = :name', ['name' => 'dongxuemin']);
			foreach($users as $user){
				echo $user->name;
			}
		insert - 插入记录,返回最后的插入ID
			DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
		update - 更新记录,返回受影响行数
			$affected = DB::update('update users set votes = 100 where name = ?', ['John']);
		delete - 删除记录,返回受影响函数
			$deleted = DB::delete('delete from users');
		statement - 运行其它通用语句(执行)
			DB::statement('drop table users');
	3>监听查询事件:
		想要获取应用中每次SQL语句的执行,可以使用listen方法,对查询日志和调试很有帮助。
		可看下,我转载的文章 'http://blog.youkuaiyun.com/beyond__devil/article/details/54171005',介绍了Laravel的服务容器机制。ServiceProvider - 服务提供者。系统默认提供了 'AppServerProvider',我们可以在里面添加 'SQL语句监听'
			use DB;
			class AppServiceProvider extends ServiceProvider{
			    public function boot()
			    {
			        DB::listen(function($query) {		// 数据监听,注册到服务中,所有请求都可以使用
			            // $query->sql
			            // $query->bindings
			            // $query->time
			        });
			    }
		    }
5.数据库事务:
	1>自动事务:
		transaction - 在一个数据库事务中运行一连串操作。如果事务闭包中抛出异常,事务将会自动回滚。如果闭包执行成功,事务将会自动提交。使用transaction方法时不需要担心手动回滚或提交。
			注意:传递的是一个闭包
			DB::transaction(function () {
			    DB::table('users')->update(['votes' => 1]);
			    DB::table('posts')->delete();
			});
	2>手动使用事务:
		DB::beginTransaction() - 开启事务
		DB::rollBack() - 回滚事务
		DB::commit() - 提交事务
6.使用多个数据库连接:
	1>connection() 方法传递 '数据库配置块名',最上面的几个配置中,除了默认的 'mysql' 配置块,还配置了一个 'mysql_2' 配置块,可以使用下面的方式连接:
		$users = DB::connection('mysql_2')->select(...);
	2>通过连接示例上的getPdo()方法,获取底层原生的PDO示例:
		$pdo = DB::connection()->getPdo();
7.查询构建器:
	1>创建查询构建器:
		table()
			table('users')
	2>获取条件筛选后的全部数据:
		get() - 返回结果同原生查询 'select()' 一致,是个数组,每个元素是一个 StdClass 对象
			$users = DB::table('users')->get();
	3>获取一行数据:
		first()
			$user = DB::table('users')->where('name', 'John')->first();
	4>不需要完整的一行,只需要某个字段的数据:
		value()
			$email = DB::table('users')->where('name', 'John')->value('email');
	5>按块获取数据表的所有数据,并将结果集填充到 '匿名函数'。例如:获取users表数据,每次获取100条:
		chunk()
			DB::table('users')->chunk(100, function($users){
				foreach($users as $user){ 		// 结果集同select()一致,是一个数组,每个元素是一个StdClass对象


				}
			})
		终止chunk块的获取,可在 '匿名函数' 中返回false:
			DB::table('users')->chunk(100, function($users){
				// 处理结果集...
				if(xxx){
					return false;		// 终止chunk循环
				}
			})
	6>获取单列数据:
		lists()
			$titles = DB::table('roles')->lists('title');		// 获取roles表的所有title字段
			foreach ($titles as $title) {
			    echo $title;
			}
		在返回数组中为列值指定自定义键(该自定义键必须是该表的其它字段列名,否则会报错),将 'name' 字段,作为 'title' 的键:
			$roles = DB::table('roles')->lists('title', 'name');
			foreach ($roles as $name => $title) {
			    echo $title;
			}
	7>聚合函数:
		count()
		max('price')
		min('price')
		avg('price')
		sum('price')
	8>排重:
		distinct()
	9>查询指定字段:
		1)select('name', 'email as user_email') 	// 注意:这里的selete()是 DB::table()->select(),同 DB::select() 是不同对象的方法
		2)已经有了查询构建起示例,希望 '再追加查询指定的列',使用 'addSelect':
			$query = DB::table('users')->select('name');
			$users = $query->addSelect('age')->get();
		3)希望在查询中,使用原生表达式(自己写的,注意SQL注入),使用 DB::raw():
			DB::table('users')->select(DB::raw('count(*) as user_count, status'));
	10>连接:
		1)内连接:
			join()
				DB::table('users')->join('contacts', 'users.id', '=', 'contacts.user_id')->get();
		2)左连接:
			leftJoin()
		3)高级连接,传递一个闭包给join(),作为第2个参数。该闭包将会返回允许你指定join子句约束的 'JoinClause对象':
			DB::table('users')->join('contacts', function ($join) {		// 闭包,闭包中有一个参数 $join - JoinClause对象
	            $join->on('users.id', '=', 'contacts.user_id')->orOn(...);
	        })->get();
	11>联合(Union)
		union() - 去除重复直
		unionAll() - 保留重复值
		示例:
			$first = DB::table('users')->whereNull('first_name');	// 第一条查询语句
			$users = DB::table('users')->whereNull('last_name')->union($first)		// 联合第一条语句
            ->get();		// 2条语句合并后,再执行语句
    12>where子句:
    	where()
    	orWhere()
    	whereBetween()
    	whereNotBetween()
    	whereIn()
    	whereNotIn()
    	whereNull()
    	whereNotNull()
    	where参数分组:
    		示例:
	    		DB::table('users')
		            ->where('name', '=', 'John')
		            ->orWhere(function ($query) {			// where可传递一个 '匿名函数',在匿名函数中,结合多个where
		                $query->where('votes', '>', 100)
		                      ->where('title', '<>', 'Admin');
		            })
		            ->get();
            SQL语句结果:
	            select * from users where name = 'John' or (votes > 100 and title <> 'Admin')
	    where exists语句:
	    	whereExists(),允许编写 'where exists' SQL子句,接收一个 '匿名函数',获取一个查询构建器实例:
	    	示例:
	    		DB::table('users')
		            ->whereExists(function ($query) {
		                $query->select(DB::raw(1))
		                      ->from('orders')
		                      ->whereRaw('orders.user_id = users.id');
		            })
		            ->get();
	    	SQL语句结果:
	    		select * from users
				where exists (
				    select 1 from orders where orders.user_id = users.id
				)
	13>排序
		orderBy()
	14>分组&限定
		groupBy()
		having()
		havingRaw() - 可使用原生SQL语句,作为having子句的值
	15>限定查询结果集:
		skip(10) - 跳过给定数目的结果
		take(5) - 获取结果集的条数
	16>插入(insert)
		insert()
			插入单条
				DB::table('users')->insert(['email' => 'john@example.com', 'votes' => 0]);
			批量插入
				DB::table('users')->insert([
				    ['email' => 'taylor@example.com', 'votes' => 0],
				    ['email' => 'dayle@example.com', 'votes' => 0]
				]);
		insertGetId()
			数据表有自增ID,插入数据想返回自增ID记录,使用:
				$id = DB::table('users')->insertGetId(
				    ['email' => 'john@example.com', 'votes' => 0]
				);
	17>更新(update)
		update()
			DB::table('users')->update(['votes' => 1]);		// 接收数组
		increment('num') - '+1'
		increment('num', 2) - '+2'
		decrement('num') - '-1'
		decrement('num', 2) - '-2'
		增、减过程中,还可以指定额外的列进行更新:
			DB::table('users')->increment('votes', 1, ['name' => 'John']);	// +1同时,更新 name 字段
	18>删除(delete)
		delete()
	19.清空(truncate)
		truncate()
	20>悲观锁
		查询构建器还包含一些方法帮助你在select语句中实现“悲观锁”。可以在查询中使用sharedLock方法从而在运行语句时带一把”共享锁“。共享锁可以避免被选择的行被修改直到事务提交:
			DB::table('users')->where('votes', '>', 100)->sharedLock()->get();
		此外你还可以使用lockForUpdate方法。“for update”锁避免选择行被其它共享锁修改或删除:
			DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();


8.迁移:
	就是数据库、数据表的结构操作,称为:'结构构建器'。
	使用的是 'Schema' 命名的Facade。
	迁移所在目录:'database/migrations'
	1>生成迁移:
		php artisan make:migration create_users_table 	// create_users_table 是迁移的文件名后缀,执行命令会生成 '2017_01_07_055954_create_users_table'
		可选参数:
			--table - 指定表明
			--create - 是否要创建一个新的数据表
			--path - 自定义迁移的输出路径(不想生成到 'database/migrations',可使用该选项)
	2>迁移方法:
		up() - 运行迁移
		down() - 撤销迁移
	3>运行迁移:
		1)运行应用中所有未执行的迁移:
			php artisan migrate
		2)在生产环境中强制运行迁移:
			php artisan migrate --force(有些迁移操作是毁灭性的,这意味着它们可能造成数据的丢失,为了避免在生产环境数据库中运行这些命令,你将会在运行这些命令之前被提示并确认)
		3)回滚最新的一次迁移:
			php artisan migrate:rollback(注意这将会回滚最后一批运行的迁移,可能包含多个迁移文件)
		4)回滚所有的应用迁移:
			php artisan migrate:reset
		5)在一条命令中,执行,回滚&迁移操作。1.回滚所有数据库迁移,2.运行所有迁移 ==> 有效的重建了整个数据库:
			php artisan migrate:refresh
			php artisan migrate:refresh --seed 	// --seed 会填充数据
	4>编写迁移:
		查看文档:http://laravelacademy.org/post/2965.html


9.填充数据:
	填充类所在目录:'database/seeds'
	默认有一个 'DatabaseSeeder' 填充类,当调用 php artisan db:seed,默认执行它里的run()方法
	1>生成填充器:
		php artisan make:seeder UserTableSeeder		// UserTableSeeder 为填充类名称
	2>填充类方法:
		默认只有一个run()方法
	3>在run()方法中,可以调用额外的填充类。使用 'call()' 方法
		public function run(){
		    Model::unguard();
		    $this->call(UserTableSeeder::class);		// 调用call(),执行 UserTableSeeder 填充类的run()
		    $this->call(PostsTableSeeder::class);
		    $this->call(CommentsTableSeeder::class);
		    Model::reguard();
		}
		采用这种方式,就可以在将巨大的一个填充文件,分散到多个文件中,我们只需要在一个初始文件中,通过call()来将多个文件结合起来!
	4>运行填充器:
		php artisan db:seed 		// 默认运行 'DatabaseSeeder' 填充类
		php artisan db:seed --class=UserTableSeeder		// 可通过 '--class' 指定要运行的填充类
	5>使用模型工厂:
		public function run(){
		    factory('App\User', 50)->create()->each(function($u) {		// factory()
		        $u->posts()->save(factory('App\Post')->make());
		    });
		}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值