1. 程式人生 > >Laravel5 操作數據庫的3種方式

Laravel5 操作數據庫的3種方式

block protect 執行 調用 維護 val 有一個 spa 而且

一、DB facade(原始查找)

        // 查詢
        $objectArray=DB::select(‘select * from student‘);
        foreach ($objectArray as $obj){
            echo $obj->id;
        }
        // 插入
        $bool=DB::insert(‘insert into student(name,age) values(?,?)‘,[‘tom‘,18]);
        // 修改
        $num=DB::update(‘update student set age=? where name=?‘
,[20,‘tom‘]); // 刪除 $num=DB::delete(‘delete from student where id=?‘,[1001]);

二、查詢構造器

Laravel查詢構造器提供了方便流暢的接口,用來建立及執行數據庫查找語法。使用了pdo參數綁定,使應用程序免於sql註入,因此傳入的參數不需要額外轉義特殊字符。基本上可以滿足所有的數據庫操作,而且在所有支持的數據庫系統上都可以執行。

查詢

        // 查詢所有數據
        $objectArray=DB::table(‘student‘)->get()->toArray();
foreach ($objectArray as $object){ echo $object->id; } // 根據條件查詢數據 $objectArray=DB::table(‘student‘)->where(‘id‘,‘>‘,1001)->get()->toArray(); foreach ($objectArray as $object){ echo $object->id; } // 根據多個條件查詢數據
$objectArray=DB::table(‘student‘)->whereRaw(‘id > ? and age = ?‘,[1001,15])->get()->toArray(); foreach ($objectArray as $object){ echo $object->id; } // 取出第一條數據(升序/降序) $object=DB::table(‘student‘)->orderBy(‘id‘,‘desc‘)->first(); echo $object->id; // 查詢指定字段名(可以指定字段名作為數組下標,不指定默認數字下標,pluck代替lists方法) $names=DB::table(‘student‘)->pluck(‘name‘,‘id‘)->toArray(); // 查詢指定的一個或多個字段 $objectArray=DB::table(‘student‘)->select(‘id‘)->get()->toArray(); // 根據指定記錄條數查詢數據並可以執行相應的方法 DB::table(‘student‘)->orderBy(‘id‘,‘desc‘)->chunk(2,function ($objects){ foreach ($objects as $object){ if ($object->id==1004){ echo ‘find‘; } } });

插入

        // 單條插入
        $bool=DB::table(‘student‘)->insert(
            [‘name‘=>‘tom‘,‘age‘=>18]
        );
        // 插入並獲取id
        $id=DB::table(‘student‘)->insertGetId(
            [‘name‘=>‘john‘,‘age‘=>10]
        );
        // 多條插入
        $bool=DB::table(‘student‘)->insert([
            [‘name‘=>‘ke1‘,‘age‘=>12],
            [‘name‘=>‘he1‘,‘age‘=>19]
        ]);

修改

       // 單條修改
        $num=DB::table(‘student‘)
            ->where(‘id‘,1002)
            ->update(
                [‘age‘=>50]
            );

        // 運行此條語句自增(默認1)
        $num=DB::table(‘student‘)->increment(‘age‘);
        // 運行此條語句自增(自增3)
        $num=DB::table(‘student‘)->increment(‘age‘,3);
        // 運行此條語句自減(默認1)
        $num=DB::table(‘student‘)->decrement(‘age‘);
        // 運行此條語句自減(自減3)
        $num=DB::table(‘student‘)->decrement(‘age‘,3);

        // 根據條件自減
        $num=DB::table(‘student‘)
            ->where(‘id‘,1002)
            ->decrement(‘age‘,3);

        // 根據條件自減並修改字段
        $num=DB::table(‘student‘)
            ->where(‘id‘,1002)
            ->decrement(‘age‘,3,[‘name‘=>‘ioc‘]);

刪除

        // 單條刪除
        $num=DB::table(‘student‘)->where(‘id‘,1003)->delete();
        // 根據條件刪除
        $num=DB::table(‘student‘)->where(‘id‘,‘>=‘,1005)->delete();
        // 刪除整個表
        $num=DB::table(‘student‘)->truncate();

聚合函數

        // 統計記錄條數
        $num=DB::table(‘student‘)->count();
        // 指定字段最大值
        $max=DB::table(‘student‘)->max(‘age‘);
        // 指定字段最小值
        $min=DB::table(‘student‘)->min(‘age‘);
        // 指定字段平均值
        $avg=DB::table(‘student‘)->avg(‘age‘);
        // 指定字段總和
        $sum=DB::table(‘student‘)->sum(‘age‘);

三、Eloquent ORM

Laravel所自帶的Eloquent ORM 是一個ActiveRecord實現,用於數據庫操作。每個數據表都有一個與之對應的模型,用於數據表交互

先新建一個model類文件,內容如下:

namespace App;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
    // 指定數據庫表名
    protected $table=‘student‘;
    // 指定主鍵
    protected $primaryKey=‘id‘;
    // 自動維護時間戳
    public $timestamps = true;
    // 指定允許批量賦值的字段(使用create方法批量增加時,需要指定允許的字段)
    protected $fillable=[‘name‘,‘age‘];
    // 指定不允許批量賦值的字段
    protected $guarded=[];

    // 自動格式化時間
    protected function getDateFormat()
    {
        return time();
    }
    // 直接返回時間戳(getDateFormat和asDateTime同時存在,asDateTime生效)
    protected function asDateTime($value)
    {
        return $value;
    }
}

接著,在控制器裏面調用新建的model類

查詢

        // 查詢所有數據
        $array=Student::all()->toArray();
        // 根據主鍵查詢
        $array=Student::find(1001)->toArray();
        // 查不到記錄報錯
        $array=Student::findOrFail(101)->toArray();

        // 【查詢構造器】查詢所有數據,在ORM中省略指定表名,其余用法一致
        $array=Student::get()->toArray();

插入

        // 模型新增數據
        $student=new Student();
        $student->name=‘yy‘;
        $student->age=13;
        $bool=$student->save();

        // 模型create方法批量新增數據
        $object=Student::create(
            [‘name‘=>‘ui‘,‘age‘=>13]
        );
        // 以屬性查找記錄,若無則新增
        $object=Student::firstOrCreate(
            [‘name‘=>‘tom‘]
        );
        // 以屬性查找記錄,若無則創建新實例,若需要保存到數據庫則需手動save()
        $object=Student::firstOrNew(
            [‘name‘=>‘tom2‘]
        );
        $bool=$object->save();

        // 【查詢構造器】插入數據
        $bool=Student::insert(
            [‘name‘=>‘mary‘,‘age‘=>18]
        );

修改

        // 模型修改數據
        $object=Student::find(1025);
        $object->name=‘kero‘;
        $bool=$object->save();

        // 【查詢構造器】根據條件修改
        $num=Student::where(‘id‘,‘=‘,1025)->update(
            [‘age‘=>10]
        );

刪除

        // 模型刪除數據
        $object=Student::find(1025);
        $bool=$object->delete();
        // 通過主鍵刪除(也可數組形式)
        $num=Student::destroy(1019,1020);

        // 【查詢構造器】根據條件刪除
        $num=Student::where(‘id‘,‘>‘,1016)->delete();

Laravel5 操作數據庫的3種方式