laravel CURD

檢索一個列值列表
DB::table("tablename")->lists('mobile'); //5.3 及以上版本 lists 改成 pluck 返回 [ "13455556666", "13455556667", "13455556668", "13455556669", ]
指定一個自定義的鍵列返回的數組
\DB::table('tablename')->lists('mobile','email');
返回
[
"aa@sina.com"=>"13022223335",
"bb@sina.com"=>"13022223336",
"cc@sina.com"=>"13022223337",
]
檢索表中的全部行

$users = DB::table('users')->get();
foreach ($users as $user)
{
    var_dump($user->name);
}
從表檢索單個行

$user = DB::table('users')->where('name', 'John')->first();
var_dump($user->name);
檢索單行單列--返回指定字段
DB::table('users')->where('name', 'John')->pluck('name');
返回數組 非字符串
["Jone"] 並非返回 "Jone"
指定一個Select子句

$users = DB::table('users')->select('name', 'email')->get();
$users = DB::table('users')->distinct()->get();
$users = DB::table('users')->select('name as user_name')->get();
where $users = DB::table('users')->where('votes', '>', 100)->get();
$users = DB::table('users')->where(['votes'=>100,'name'=>'zhangsan'])->get();
OR 

$users = DB::table('users')->where('votes', '>', 100)->orWhere('name', 'John')->get();

Where Between

$users = DB::table('users')->whereBetween('votes', array(1, 100))->get();

Where Not Between

$users = DB::table('users')->whereNotBetween('votes', array(1, 100))->get();

Where In With An Array

$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();

$users = DB::table('users')->whereNotIn('id', array(1, 2, 3))->get();

Using Where Null To Find Records With Unset Values

$users = DB::table('users')->where('parent_id',1)->whereNull('updated_at')->get();

Order By
, Group By, And Having

$users = DB::table('users')->orderBy('name', 'desc')->groupBy('count')->having('count', '>', 100)->get();

Offset
& Limit

$users = DB::table('users')->skip(10)->take(5)->get();
Joins
DB::table('users')
  ->join('contacts', 'users.id', '=', 'contacts.user_id')
  ->join('orders', 'users.id', '=', 'orders.user_id')
  ->select('users.id', 'contacts.phone', 'orders.price')
  ->get();

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();
//on 多個條件
DB::table('users')   ->join('contacts', function($join)   {   $join->on('users.id', '=', 'contacts.user_id')->on(...);   }) ->get();
DB::table('users')   ->join('contacts', function($join)   {   $join->on('users.id', '=', 'contacts.user_id')   ->where('contacts.user_id', '>', 5);   })   ->get();
聚合
$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');
遞增或遞減一個列的值
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, array('name' => 'John'));
Inserts 
DB::table('users')->insert(
array('email' => 'john@example.com', 'votes' => 0)
);

$id = DB::table('users')->insertGetId(
array('email' => 'john@example.com', 'votes' => 0)
);

多個記錄插入到表中

DB::table('users')->insert(array(
array('email' => 'taylor@example.com', 'votes' => 0),
array('email' => 'dayle@example.com', 'votes' => 0),
));
Updates
DB::table('users')
->where('id', 1)
->update(array('votes' => 1));
Deletes
刪除表中的記錄

DB::table('users')->where('votes', '<', 100)->delete();
 
刪除表中的全部記錄

DB::table('users')->delete();

清空一個表

DB::table('users')->truncate();
共享鎖
DB::table('users')->where('votes', '>',
100)->sharedLock()->get();

更新「鎖」
DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();

\DB::connection()->getPdo()->exec($sql)

 

事務 使用匿名函數 任何一個異常都會觸發回滾

        return \DB::transaction(function() use($user_params, $staff_params) {
            //寫管理員進入user表
            $user_id = DB::table(User::TABLE_NAME)
                ->insertGetId($user_params);
            if(!$user_id) throw new Exception("寫入user表失敗");

            $staff_params[Staff::DB_FIELD_USER_ID] = $user_id;
            $staff_id=DB::table(Staff::TABLE_NAME)
                ->insertGetId($staff_params);
            if(!$staff_id) throw new Exception("寫入staff表失敗");

            return $staff_id;
        });

 

直接使用語句
$ret = DB::select("select * from tablename where id=123"); //返回一個二維數組
或者
$ret = DB::select("select * from tablename where id=?",[123]); //返回一個二維數組
使用命名綁定來執行查詢
$results = DB::select('select * from users where id = :id', ['id' => 1]);
 
 


DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
$affected = DB::update('update users set votes = 100 where name = ?', ['John']);
 


$deleted = DB::delete('delete from users');
DB::statement('drop table users');
 

 

//chunk()每次查n條  
$student=DB::table("vipinfo")->chunk(2,function($students){  //每次查2條  
    var_dump($students);  
    if(.......) return false;  //在知足某個條件下使用return就不會再往下查了  
});  

 

打印sql
\DB::connection()->enableQueryLog();#開啓log $aa = \DB::table(tablename)->first(); $log = \DB::getQueryLog(); dd($log); //打印 array:1 [ 0 => array:3 [ "query" => "select * from `fuli_xwc_merchant` limit 1" "bindings" => [] "time" => 29.27 ] ]

 

手動使用事務


若是你想要手動開始事務從而對回滾和提交有一個完整的控制,可使用 DB 門面的beginTransaction 方法:

DB::beginTransaction();
你能夠經過 rollBack 方法回滾事務:

DB::rollBack();
最後,你能夠經過 commit 方法提交事務:

DB::commit();
注意:使用 DB 門面的事務方法還能夠用於控制查詢構建器和 Eloquent ORM 的事務。

 likesql

$users = DB::table('users')
            ->where('name', 'like', 'T%')
            ->get();
$users = DB::table('users')
            ->where('votes', '>=', 100)
            ->get();

$users = DB::table('users')
            ->where('votes', '<>', 100)
            ->get();

$users = DB::table('users')->where([
    ['status', '=', '1'],
    ['subscribed', '<>', '1'],
])->get();
$users = DB::table('users')
                ->where('votes', '>', 100)
                ->orWhere('name', 'John')
                ->get();
$users = DB::table('users')
                ->whereBetween('votes', [1, 100])->get();

  null數組

$users = DB::table('users')
                ->whereNull('updated_at')
                ->get();
$users = DB::table('users')
                ->whereNotNull('updated_at')
                ->get();

  從一張表中獲取一行/一列函數

$user = DB::table('users')->where('name', 'John')->first();
echo $user->name;//該方法將會返回單個 StdClass 對象:

$email = DB::table('users')->where('name', 'John')->value('email');

 

DB:rawpost

\DB::table(\DB::raw("xl_channel_goods as a"))
           ->whereIn(ChannelGood::DB_FIELD_CHANNEL_GOODS_CODE, $codes)
            ->get([
                'a.*',
                \DB::raw("(select goods_name from xl_goods as b where a.goods_sn=b.goods_sn) as goods_name"),
                \DB::raw("(select group_concat(upc)  from xl_goods_upc as c where a.goods_sn=c.goods_sn group by c.goods_sn) as upc")
            ]);
相關文章
相關標籤/搜索