• laravel 控制器类DB类操作


    例子:TrGo表(trgo_chip):

    laravel框架建立:TrGoModel

    <?php
    namespace TrChaosModel;
    
    class TrGoModel extends Model
    {
             protected $table = 'trgo_chip';
             protected $fillable = [
              'id','item_id','sku_id','item_num','chip_code','created_at','updated_at','deleted_at'
    ];
    }
    
    ?>

    从数据表中取得所有的列:

    <?php
    $users = DB::table('user')->get();
    foreach($users as $user){
        var_dump($user->name);
    }
    
    $users->toArray(); // 转换成数组
    
    ?>  

    从数据表中取得单一数据列:

    <?php
    DB::table('users')->where('name', 'John')->first();
    

    从数据表中取得单一数据列的单一字段:

    <?php
    
    $name = DB::table('users')->where('name','John')->pluck('name');
    
    换做Laravel中的写法,先定义好Model
    // 芯片记录
    $chip_codes = TrGoModel::query()->where('deleted_at', '=', null)->pluck('chip_code');  

    从数据表中取得单一字段值的列表:

    <?php
    
    $roles = DB::table('roles')->lists('title');
    
    // 重新命名title值为name
    $roles = DB::table('roles')->lists('title','name');
    

    从指定查询子句:

    <?php
    $users = DB::table('users')->select('name','email')->get();
    
    $users = DB::table('users')->distinct()->get();
    
    $users = DB::table('users')->select('name as user_name')->get();
    
    // 增加查询子句到现有的查询中
    $users = DB::table('users')->select('name')->addSelect('age')->get();
    

    where,or的用法:

    <?php
    $users = DB::table('users')->where('votes', '>', 100)->orWhere('name','John')->get();
    
    $users = DB::table('users')->whereBetween('votes',[1,100])->get();
    
    $user = DB::table('users')->whereNotBetween('votes',[1,100])->get();
    
    $users = DB::table('users')->whereIn('id',[1,2,3])->get();
    $users = DB::table('users')->whereNotIn('id',[1,3])->get();
    
    $users = DB::table('users')->whereNull('updated_at')->get();
    
    $admin = DB::table('users')->whereId(1)->first();
    $john = DB::table('users')->whereIdAndEmail(2, 'john@ss.com')->first();
    $jane = DB::table('users')->whereNameOrAge('jane',22)->first();
    ?>
    

    排序(Order By) 、分群(Group By) 及Having的用法:

    <?php
    $users = DB::table('users')->orderBy('name','desc')->groupBy('count')->having('count','>',100)->get();
    
    // 偏移(offset)及限制Limit
    $users = DB::table('users')->skip(10)->table(5)->get(); 

    Joins:

    <?php
    DB::table('users')->join('contacts','users.id','=','contacts.user_id')
    ->join('orders','users.id','=','orders.user_id')
    ->select('user.id','contacts.phone','orders.price')
    ->get();
    
    // LEFT JOIN
    DB::table('users')->LEFTJoin('posts','users.id','=','posts.user_id')->get();
    
    DB::table('users')->join('contacts',function($join){
         $join->on('users.id','=','contacts.user_id')->orOn(...);
    })->get();
    
    DB::table('users')
            ->join('contacts', function($join)
            {
                $join->on('users.id', '=', 'contacts.user_id')
                     ->where('contacts.user_id', '>', 5);
            })
            ->get();
    

     

    Wheres:

    <?php
    
    //有些时候你需要更高级的 where 子句,如「where exists」或嵌套的群组化参数。Laravel //的查询构造器也可以处理这样的情况:
    
    DB::table('users')
                ->where('name', '=', 'John')
                ->orWhere(function($query)
                {
                    $query->where('votes', '>', 100)
                          ->where('title', '<>', 'Admin');
                })
                ->get();
    /*
    上面的查找语法会产生下方的 SQL:
    select * from users where name = 'John' or (votes > 100 and title <> 'Admin')
    */
    
    //Exists 语法
    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
    )
    */

    whereRaw(可以加原生语句):例如:
    TrGoModel::query()->whereRaw('id = 286')->first();

    聚合:

    $users = DB::table('users')->count();
    
    $price = DB::table('orders')->max('price');
    
    $price = DB::table('orders')->min('price');
    
    $price = DB::table('orders')->avg('price');
    
    $total = DB::table('users')->sum('votes');
    

      

    原生表达式

    $users = DB::table('users')
                         ->select(DB::raw('count(*) as user_count, status'))
                         ->where('status', '<>', 1)
                         ->groupBy('status')
                         ->get();

    whereRaw(可以加原生语句):例如:
    TrGoModel::query()->whereRaw('id = 286')->first();

    添加

    添加数据进数据表
    DB::table('users')->insert(
        ['email' => 'john@example.com', 'votes' => 0]
    );
    添加自动递增 (Auto-Incrementing) ID 的数据至数据表
    如果数据表有自动递增的ID,可以使用 insertGetId 添加数据并返回该 ID:
    
    $id = DB::table('users')->insertGetId(
        ['email' => 'john@example.com', 'votes' => 0]
    );
    注意: 当使用 PostgreSQL 时,insertGetId 方法会预期自动增加的字段是以「id」为命名。
    
    添加多个数据进数据表
    DB::table('users')->insert([
        ['email' => 'taylor@example.com', 'votes' => 0],
        ['email' => 'dayle@example.com', 'votes' => 0]
    ]);
    

    更新

    更新数据表中的数据
    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']);
    

     

    删除

    删除数据表中的数据
    DB::table('users')->where('votes', '<', 100)->delete();
    删除数据表中的所有数据
    DB::table('users')->delete();
    清空数据表
    DB::table('users')->truncate();
    

    Unions

    查询构造器也提供一个快速的方法去「合并 (union)」两个查找的结果:
    
    $first = DB::table('users')->whereNull('first_name');
    
    $users = DB::table('users')->whereNull('last_name')->union($first)->get();
    unionAll 方法也可以使用,它与 union 方法的使用方式一样。
    

      

    悲观锁定 (Pessimistic Locking)

      

    查询构造器提供了少数函数协助你在 SELECT 语句中做到「悲观锁定」。
    
    想要在 SELECT 语句中加上「Shard lock」,只要在查找语句中使用 sharedLock 函数:
    
    DB::table('users')->where('votes', '>', 100)->sharedLock()->get();
    要在 select 语法中使用「锁住更新(lock for update)」时,你可以使用 lockForUpdate方法:
    
    DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();
    

      

    从数据表中分块查找数据列:

    <?php
    $users = DB::table('users')->chunk(100, function(){
         foreach($users as $user){
              return false; // 返回false停止处理接下来的数据列
         }
    
    })
    ?> 
  • 相关阅读:
    SDUT 2143 图结构练习——最短路径 SPFA模板,方便以后用。。 Anti
    SDUT ACM 1002 Biorhythms 中国剩余定理 Anti
    nyist OJ 119 士兵杀敌(三) RMQ问题 Anti
    SDUT ACM 2157 Greatest Number Anti
    SDUT ACM 2622 最短路径 二维SPFA启蒙题。。 Anti
    二叉索引树 区间信息的维护与查询 Anti
    SDUT ACM 2600 子节点计数 Anti
    UVA 1428 Ping pong 二叉索引树标准用法 Anti
    2010圣诞Google首页效果
    Object
  • 原文地址:https://www.cnblogs.com/yaoyao1556/p/9335909.html
Copyright © 2020-2023  润新知