laravel[数据库] 总结

来源:互联网 发布:删除内置软件 编辑:程序博客网 时间:2024/06/02 03:55
数据库:
  SQL Server  配置:config/database.php
  
    'sqlsrv' => [
    'driver' => 'sqlsrv',
    'host' => env('DB_HOST', 'localhost'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => 'utf8',
    'prefix' => '',
             ],
读写分离:
    'mysql' => [
     'read' => [
         'host' => '192.168.1.1',
      ],
     'write' => [
         'host' => '196.168.1.2'
      ],
    'sticky'    => true,
    'driver'    => 'mysql',
    'database'  => 'database',
    'username'  => 'root',
    'password'  => '',
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix'    => '',
      ],
sticky 是一个可选的选项,它的具体作用是:若在当前的请求周期内,
数据库曾经被写入过一些数据,sticky 选项会立即将这些数据读出来

  use Illuminate\Support\Facades\DB;
$users = DB::connection('foo')->select(...);   //链接数据库(可多个)
$pdo = DB::connection()->getPdo();
链接好数据库的CURD
R:
$results = DB::select('select * from users where id = :id', ['id' => 1]);
$users = DB::table('users')->get();    //多行
$user = DB::table('users')->where('name', 'John')->first();   //单行
$email = DB::table('users')->where('name', 'John')->value('email');  //取单个值
$titles = DB::table('roles')->pluck('title');    //取单个列的值  以数组形式
$roles = DB::table('roles')->pluck('title', 'name');      //取单个title的值,自定义数组的key为name
DB::table('users')->orderBy('id')->chunk(100, function ($users) {
    foreach ($users as $user) {
        //
    }
});          //将结果分块  数据量大时
$users = DB::table('users')->可接count()或max()或min()或avg()或sum()

select 子句
$users = DB::table('users')->select('name', 'email as user_email')->get();  //可以实现查询某个字段
$users = DB::table('users')->distinct()->get();   //返回不重复的结果
$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();     //添加一个字段的查询
$users = DB::table('users')
                     ->select(DB::raw('count(*) as user_count, status'))
                     ->where('status', '<>', 1)
                     ->groupBy('status')
                     ->get();
         DB::raw()  //可以防SQL注入    对于查询某个字段或数据时
join查询
$users = DB::table('users')
            ->join('contacts', 'users.id', '=', 'contacts.user_id')
            ->join('orders', 'users.id', '=', 'orders.user_id')
            ->select('users.*', 'contacts.phone', 'orders.price')
            ->get();      //可以多个两表联查
$users = DB::table('users')
            ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
            ->get();     //左链接
$users = DB::table('sizes')
            ->crossJoin('colours')
            ->get();      //交叉连接
高级 Join 语法
$users = DB::table('users')    我们传递一个闭包作为 join 方法的第二个参数来作为开始
            ->join('contacts', function ($join) {  
              $join->on('users.id', '=', 'contacts.user_id')->orOn(...);
            })
            ->get();
合并两个查询:
$first = DB::table('users')
            ->whereNull('first_name');
$users = DB::table('users')
            ->whereNull('last_name')
            ->union($first)     //使用union进行合并,也可以使用unionAll方法用法一样
            ->get();
where的查询:
    ->where('name', 'like', 'T%')
    ->where('votes', '>=', 100)
    ->where('votes', '=', 100)
    ->where('votes', 100)
    ->where([
     ['status', '=', '1'],
     ['subscribed', '<>', '1'],
        ])
Or 语法
 ->where('votes', '>', 100)
        ->orWhere('name', 'John')
 ->whereBetween('votes', [1, 100])
 ->whereNotBetween('votes', [1, 100])
 ->whereIn('id', [1, 2, 3])   //方法验证字段的值包含在指定的数组内
 ->whereNotIn('id', [1, 2, 3])  // 方法验证字段的值 不 包含在指定的数组内
 ->whereNull('updated_at')   //方法验证字段的值为  NULL
 ->whereNotNull('updated_at')   //方法验证字段的值 不 为 NULL
whereDate / whereMonth / whereDay / whereYear   //方法比较某字段的值与指定的时间是否相等
whereColumn
->whereColumn('first_name', 'last_name')    //用来检测两个列的数据是否一致
OrderBy查询:
 ->orderBy('name', 'desc')
 ->latest()    //最近
 ->oldest()    //按时间正序排
inRandomOrder查询
 ->inRandomOrder()   //可以将查询结果虽积极排序
groupBy / having / havingRaw
 用来对查询结果进行分组
     ->groupBy('account_id')
        ->having('account_id', '>', 100)
 ->groupBy('department')
        ->havingRaw('SUM(price) > 2500')
skip / take
 ->skip(10)->take(5)
 ->offset(10)->limit(5)     //两方法相同都是限制查询结果数量或略过指定数量
 
 

C:
DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
U:
$affected = DB::update('update users set votes = 100 where name = ?', ['John']);
D:
$deleted = DB::delete('delete from users');
DB::statement('drop table users');
原创粉丝点击