34
Go to list of users who liked
35
Share on X(Twitter)
Share on Facebook
More than 5 years have passed since last update.
複雑なクエリを書こうとするほどDB::query()に頼りがちになる罠。
仕事中に書いていたクエリビルダの個人的なメモをまとめます。
Select
as_array()は好みの問題。個人的には便利なので使用しています。
// 基本形DB::select()->from('hoge')->execute()->as_array();// joinDB::select()->from('hoge')->join('moge','left')->on('hoge.moge_id','=','moge.id')->execute()->as_array();// order byDB::select()->from('hoge')->order_by('hoge.pub_date','desc')->execute()->as_array();// group_byDB::select()->from('hoge')->group_by('hoge.moge_id')->execute()->as_array();// sumを取りたいDB::select(DB::expr('sum(hoge.visitor)'))->from('hoge')->execute()->as_array();DB::expr()
select()内に文字を書くと、例えばDB::select('hoge')->...はselect hoge from ~ではなく、select 'hoge' from ~の形に変換されます。
ここに素のままでDB::select('sum(hoge)')->...と記述してしまうと、select 'sum(hoge)' from ~になってしまい、「sum(hoge)なんてカラムはないよ」、というエラーが発生してしまいます。
この厄介なクォーテーションを付けさせないのがexpr()関数です。
公式リファレンスはこちら:FuelPHP公式リファレンス
見つけねえよこんなの。
Insert
// 基本形$res=DB::insert('hoge')->set(array('name'=>'仙臺四郎','age'=>28))->execute();/* * $res[0]=insertしたレコードのID */insert()の戻り値マジ便利。
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme