TP5中CURD那點事兒(二)

return返回
    return 不能返回數(shù)組
    $data = [a,c,d];
    return json($data);
    return json($data,201); 改狀態(tài)碼
    return xml($data);
    return $this->fetch();
    return view();

跳轉(zhuǎn)
    $this->success('成功','index/hello');
    $this->error('失敗','/admin/index/index.html?name=lisa&sex=0');
    $this->redirect('同上');

數(shù)據(jù)庫基本操作:

查詢構(gòu)造器:CURD操作可直接傳數(shù)組
    1、表名必須帶前綴的完整表名;
    Db::table('tp_data') ->insert(['id'=>6,'name'=>'thinkphp']);
    Db::table('tp_data') ->where('id',2)-update(['date' => '2']);
    2、表名不帶前綴;
        Db::name('data')->.....
    3、助手函數(shù),也不帶前綴,還不用引入,直接用
    db('data')->......


事務(wù)的應(yīng)用
    首先保證存儲引擎為InnoDB
    需要把要執(zhí)行的操作放進(jìn)閉包,即可自動完成事務(wù)
    Db::transaction(function (){
        Db::table('tp_data')->delete(2);
        Db::table('tp_data')->insert(['id' => 9,'name'=>'thinkphp','status'='1']);
    });

    手動控制事務(wù)的提交
    //啟動食事務(wù)
    Db::startTrans();
    try{
            Db::table('tp_data')->delete(2);
            Db::table('tp_data')->insert(['id' => 9,'name'=>'thinkphp','status'='1']);
            //提交事務(wù)
            Db::commit();
    } catch( \Exception $e) {
            //回滾事務(wù)
        Db::rollback();
    }


查詢語言:
    Db::name('data')->where('id','between',[1,9])->select();
    Db::name('data')->where('name',null);
    Db::name('data')->where('id','exp',"in(1,2,3,4)")->select();
    Db::name('data')->where('id','exp',">1")->select();
    Db::name('data')->where('id','exp',">1 and name='zhangsan'")->select();
    Db::name('data')->where('id','>=',1)
                    ->where('name','like','%php%')
                    ->select();//兩個where為and關(guān)系
    Db::name('data')->where(['id'=>['>='1],
                            'name'=>['like','%php%']
                            ])
                    ->select();

批量查詢
    $res = Db::name('data')
        ->where([
        'id'=>[['in',[5,6,7,8]],['<='1],'or'],
        'name'=>['like','%php%'],
        ])
        ->limit(10)
        ->select();

快捷查詢:
    $res = Db::name('data')
        ->where('id&status','>',0)     ('id | status','>' 0 );
        ->limit(10)
        ->select();


視圖查詢
    $res = Db::view('table1','id,name,status')
        ->view('table2',['nickname'=>'user_name','mobile','email'],table2.user_id=table1.id)
        ->order('id desc')
        ->select();

Query 對象使用
    $query = new \think\db\Query;
    $query = name('data')->where('name','like','%php%')
        ->where('id','>=','1')
        ->limit(10);
    $res = Db::select($query);
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容