主頁 > 知識庫 > laravel框架數(shù)據(jù)庫操作、查詢構(gòu)建器、Eloquent ORM操作實(shí)例分析

laravel框架數(shù)據(jù)庫操作、查詢構(gòu)建器、Eloquent ORM操作實(shí)例分析

熱門標(biāo)簽:銀行業(yè)務(wù) 科大訊飛語音識別系統(tǒng) Linux服務(wù)器 團(tuán)購網(wǎng)站 服務(wù)器配置 Mysql連接數(shù)設(shè)置 電子圍欄 阿里云

本文實(shí)例講述了laravel框架數(shù)據(jù)庫操作、查詢構(gòu)建器、Eloquent ORM操作。分享給大家供大家參考,具體如下:

1、連接數(shù)據(jù)庫

laravel連接數(shù)據(jù)庫的配置文件位于config/database.php中,在其中connection字段中包含laravel所支持的數(shù)據(jù)庫的配置信息,可以看到其中有主機(jī)、端口、數(shù)據(jù)庫、用戶名、密碼等信息:

'mysql' => [
  'driver' => 'mysql',
  'host' => env('DB_HOST', 'localhost'),
  'port' => env('DB_PORT', '3306'),
  'database' => env('DB_DATABASE', 'forge'),
  'username' => env('DB_USERNAME', 'forge'),
  'password' => env('DB_PASSWORD', ''),
  'charset' => 'utf8',
  'collation' => 'utf8_unicode_ci',
  'prefix' => '',
  'strict' => false,
  'engine' => null,
],

其中都是引入env文件中的默認(rèn)值,laravel目錄最外層有.env文件,在其中配置對應(yīng)的默認(rèn)值

DB_HOST=數(shù)據(jù)庫服務(wù)器地址
DB_PORT=數(shù)據(jù)庫端口
DB_DATABASE=數(shù)據(jù)庫名
DB_USERNAME=用戶名
DB_PASSWORD=密碼

2、原生SQL操作數(shù)據(jù)庫

在controller中對數(shù)據(jù)庫進(jìn)行增刪改查的操作

public static function testDB(){
  //增加一條數(shù)據(jù)
  DB::insert("insert into student(name,age) values(?,?)",['sandy',19]);
  //刪除一條數(shù)據(jù)
  DB::delete('delete from student where name=?',['sandy']);
  //修改一條數(shù)據(jù)
  DB::update('update student set sex=? where name=?',['男','tory']);
  //查詢數(shù)據(jù)
  $res=DB::select('select * from student');
  //進(jìn)行數(shù)據(jù)庫通用操作
  DB::statement('drop table users');
  //打印結(jié)果
  dd($res);
}

其中通過?占位符的方式進(jìn)行了參數(shù)綁定,以此來防止數(shù)據(jù)庫注入攻擊,也可以通過命名綁定的方式:   

$res = DB::select('select * from users where id = :id', ['id' => 1]);

3、通過查詢構(gòu)建器操作數(shù)據(jù)庫

Laravel將常用的數(shù)據(jù)庫操作封裝為接口函數(shù)提供給用戶調(diào)用,從而使數(shù)據(jù)庫操作更為便捷,這些接口就是查詢構(gòu)建器(query builder)。而且通過PDO綁定的方式避免SQL注入攻擊,在使用查詢構(gòu)建器時(shí)不必考慮過濾用戶輸入。

3.1、得到結(jié)果集

lavarel查詢的返回結(jié)果集合是StdClass,可以通過$res->name類似訪問對象屬性的方式訪問返回值。如果要查詢整個(gè)表使用get(),查詢表中一條數(shù)據(jù)使用first(),查詢一條數(shù)據(jù)的某個(gè)字段用value(),查詢表中所有數(shù)據(jù)的某個(gè)字段用pluck()

//get()返回表中所有數(shù)據(jù)
$res=DB::table('student')->get();
//first()返回結(jié)果集中的第一條數(shù)據(jù)
$res=DB::table('student')->where('id','1001')->first();
//value()返回一條數(shù)據(jù)中的指定字段
$res=DB::table('student')->where('id','1003')->value('name');
//pluck()返回結(jié)果集中name字段的所有值
$res=DB::table('student')->pluck('name');

當(dāng)結(jié)果集中的數(shù)據(jù)過多時(shí),可以通過分塊的方式返回結(jié)果集,chunk函數(shù)第一個(gè)參數(shù)為分塊的大?。ㄒ悦繅K2個(gè)數(shù)據(jù)的方式返回結(jié)果集),第二個(gè)參數(shù)為回調(diào)函數(shù),當(dāng)其返回false時(shí)就停止結(jié)果集的返回:

DB::table('student')->chunk(2,function ($res){
  foreach ($res as $user){
    var_dump($user);
    if ($user->id >=1003) return false;
  }
});

3.2、增刪改查

//增加一條數(shù)據(jù)
DB::table('student')->insert(['name'=>'李four','sex'=>'男','age'=>22]);
//增加多條數(shù)據(jù)
DB::table('student')->insert([
  ['name'=>'wang五','sex'=>'女','age'=>21],
  ['name'=>'zhao六','sex'=>'女','age'=>20],
]);
//刪除數(shù)據(jù)
DB::table('student')->where('id','>=',1006)->delete();
//刪除整個(gè)表
DB::table('student')->truncate();
//修改數(shù)據(jù)
DB::table('student')->where('id',1005)->update(['sex'=>'女','age'=>21]);
//自增increment、自減decrement,默認(rèn)增1
DB::table('student')->where('id',1005)->increment('age',2);
//自增同時(shí)可以進(jìn)行修改
DB::table('student')->where('id',1005)->increment('age',1,['sex'=>'女']);
//查詢指定字段
$res=DB::table('student')->select('name','age')->get();

3.3、查詢條件

通過查詢構(gòu)建器的where方法可以添加數(shù)據(jù)庫查詢條件,where()接收三個(gè)參數(shù):字段名、操作符、值,操作符如果是'='可以省略,例如查詢id>=1003的數(shù)據(jù):

$res=DB::table('student')->where('id','>=',1003)->get();

也可以通過條件數(shù)組傳入多個(gè)限制條件,比如查詢id>=1003并且id1005:

$res=DB::table('student')->where([
  ['id','>=',1003],
  ['id','',1005]
])->get();

通過orwhere()來連接兩個(gè)并列條件,例如查詢id>=1003或者id1002的數(shù)據(jù):

$res=DB::table('student')->where('id','>=',1003)->orwhere('id','',1002)->get();

whereBetween()查詢位于某個(gè)區(qū)間的數(shù)據(jù):

$res=DB::table('student')->whereBetween('id',[1003,1006])->get();

當(dāng)when()來判斷某個(gè)查詢是否執(zhí)行,例如當(dāng)$order為true時(shí),才會執(zhí)行排序:

$order=false;
$res=DB::table('student')->when($order,function ($query){
  return $query->orderBy('age','desc');       //$order為true時(shí)才執(zhí)行此語句
})->get();

3.4、排序、分組、限定

//orderBy對age字段升序
$res=DB::table('student')->orderBy('age','asc')->get();
//按照create_at字段進(jìn)行時(shí)間排序
$res=DB::table('student')->latest('create_at')->get();
//分組
$res=DB::table('student')->groupBy('sex')->get();
//跳過一條數(shù)據(jù)后返回2條數(shù)據(jù)
$res=DB::table('student')->skip(1)->limit(2)->get();

3.5、聚合函數(shù)

laravel查詢構(gòu)建器還提供了聚合函數(shù)用于操作查詢的結(jié)果集,包括count(計(jì)數(shù))、sum(求和)、avg(平均值)、max(最大值)、min(最小值),例如求年齡平均值:

$res=DB::table('student')->avg('age');

4、Eloquent ORM

ORM是對象關(guān)系映射(Object Relational Mapping)的簡稱,是一種實(shí)現(xiàn)面向?qū)ο缶幊陶Z言里不同類型系統(tǒng)的數(shù)據(jù)之間的轉(zhuǎn)換的技術(shù),即將數(shù)據(jù)庫中的數(shù)據(jù)按照對象的形式進(jìn)行組織,可以便于面向?qū)ο蟮某绦蜻M(jìn)行數(shù)據(jù)庫操作,之前在學(xué)習(xí)mongoDB時(shí)使用過mongoose ORM組織mongoDB ,當(dāng)時(shí)還沒有意識到這是orm。

Laravel內(nèi)置的Eloquent ORM提供了一種便捷的方式幫助你組織數(shù)據(jù)庫數(shù)據(jù),每張數(shù)據(jù)表都對應(yīng)一個(gè)與該表進(jìn)行交互的模型(Model),通過Model類,你可以對數(shù)據(jù)表進(jìn)行查詢、插入、更新、刪除等操作。Eloquent ORM本質(zhì)上是查詢構(gòu)建器,因此上面查詢構(gòu)建器所使用的方法Eloquent都可以使用。

4.1、創(chuàng)建Model

在app文件夾下新建model文件,每個(gè)數(shù)據(jù)庫都需要對應(yīng)一個(gè)model,例如創(chuàng)建一個(gè)Student模板類:

namespace App;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
  //指定對應(yīng)的表
  protected $table='student';
  //指定主鍵
  protected $primaryKey='id';
  //允許批量賦值的字段
  protected $fillable=['name','age'];
  //不允許批量賦值的字段
  protected $guarded=['created_at'];
}

模板類會默認(rèn)對應(yīng)小寫首字母末尾加s的數(shù)據(jù)庫,例如Student模板會在當(dāng)前數(shù)據(jù)庫中查找students表。如果需要自定義表名,則需要重寫$table變量來指定表名。

Eloquent默認(rèn)的主鍵為'id',且該字段為自增int型,如果需要自定義主鍵,可以通過$primaryKey來指定。

Eloquent默認(rèn)會管理數(shù)據(jù)表的創(chuàng)建時(shí)間、更新時(shí)間,對應(yīng)數(shù)據(jù)表中的created_at、updated_at字段,你需要在創(chuàng)建表時(shí)包含這兩個(gè)字段。如果不需要管理,可以令public $timestamps = false;。否則會報(bào)錯(cuò)

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'updated_at' in 'field list'

也可以自定義兩個(gè)時(shí)間為你數(shù)據(jù)庫中的字段:

const CREATED_AT = 'my_create';
const UPDATED_AT = 'my_update';

4.2、Eloquent操作數(shù)據(jù)庫

  • 新增數(shù)據(jù)有兩種方法,一是通過新建ORM實(shí)例,而是通過create方法。在使用create批量添加時(shí),需要在模板中通過$fillable指定可以賦值的字段,也可以$guard指定不允許賦值的字段。
//新建實(shí)例并賦值、保存
$stu=new Student();
$stu->name='orm2';
$stu->save();
//create方法批量添加數(shù)據(jù)
Student::create(['name'=>'orm3','age'=>13]);

  • 刪除數(shù)據(jù)也有兩種方法,一是通過find方法刪除指定主鍵,二是通過查詢構(gòu)建器:
//destroy刪除指定主鍵值
Student::destroy(1006,1007);
//通過查詢構(gòu)建器刪除
Student::where('id',1008)->delete();

  • 修改數(shù)據(jù):①通過ORM實(shí)例來修改并保存②通過查詢構(gòu)建器
//通過返回Student對象進(jìn)行修改
$stu=Student::find(1005);
$stu->age=21;
$stu->save();
//通過查詢構(gòu)建器修改
Student::where('id',1005)->update(['age'=>22]);

  • 查找數(shù)據(jù):
//查詢表中所有記錄
$table=Student::all();
//根據(jù)id查詢一條數(shù)據(jù)
$row=Student::find(1002);
dd($table);

當(dāng)然也可以通過構(gòu)建器的get()、first()來獲取數(shù)據(jù)

通過上面的增刪改查可以看出Eloquent可以使用查詢構(gòu)建器的所有方法,除了增刪改查外,還有where、聚合函數(shù)等。

更多關(guān)于Laravel相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Laravel框架入門與進(jìn)階教程》、《php優(yōu)秀開發(fā)框架總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》

希望本文所述對大家基于Laravel框架的PHP程序設(shè)計(jì)有所幫助。

您可能感興趣的文章:
  • laravel5.6 框架操作數(shù)據(jù) Eloquent ORM用法示例
  • Laravel 手動(dòng)開關(guān) Eloquent 修改器的操作方法
  • Laravel框架Eloquent ORM新增數(shù)據(jù)、自定義時(shí)間戳及批量賦值用法詳解
  • Laravel框架Eloquent ORM簡介、模型建立及查詢數(shù)據(jù)操作詳解
  • Laravel框架Eloquent ORM修改數(shù)據(jù)操作示例
  • Laravel Eloquent分表方法并使用模型關(guān)聯(lián)的實(shí)現(xiàn)
  • laravel7學(xué)習(xí)之無限級分類的最新實(shí)現(xiàn)方法
  • laravel admin實(shí)現(xiàn)分類樹/模型樹的示例代碼
  • 如何使用Laravel Eloquent來開發(fā)無限極分類

標(biāo)簽:蚌埠 衢州 棗莊 衡水 大理 江蘇 萍鄉(xiāng) 廣元

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《laravel框架數(shù)據(jù)庫操作、查詢構(gòu)建器、Eloquent ORM操作實(shí)例分析》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266