基本用法

2018-02-24 15:52 更新

我們先從建立一個(gè) Eloquent 模型開始。模型通常放在 app 目錄下,但是您可以將它們放在任何地方,只要能通過 composer.json 自動(dòng)載入。所有的 Eloquent 模型都繼承于 Illuminate\Database\Eloquent\Model 。

定義一個(gè) Eloquent 模型

class User extends Model {}

你也可以通過 make:model 命令自動(dòng)生成 Eloquent 模型:

php artisan make:model User

注意:我們并沒有告訴 Eloquent User 模型會(huì)使用哪個(gè)數(shù)據(jù)庫表。若沒有特別指定,系統(tǒng)會(huì)默認(rèn)自動(dòng)對(duì)應(yīng)名稱為「類名稱的小寫復(fù)數(shù)形態(tài)」的數(shù)據(jù)庫表。所以,在上面的例子中, Eloquent 會(huì)假設(shè) User 模型將把數(shù)據(jù)存在 users 數(shù)據(jù)庫表。您也可以在類中定義 table 屬性自定義要對(duì)應(yīng)的數(shù)據(jù)庫表。

class User extends Model {
    protected $table = 'my_users';
}

注意: Eloquent 也會(huì)假設(shè)每個(gè)數(shù)據(jù)庫表都有一個(gè)字段名稱為 id 的主鍵。您可以在類里定義 primaryKey 屬性來重寫。同樣的,您也可以定義 connection 屬性,指定模型連接到指定的數(shù)據(jù)庫連接。

定義好模型之后,您就可以從數(shù)據(jù)庫表新增及獲取數(shù)據(jù)了。注意在默認(rèn)情況下,在數(shù)據(jù)庫表里需要有 updated_at 和 created_at 兩個(gè)字段。如果您不想設(shè)定或自動(dòng)更新這兩個(gè)字段,則將類里的 $timestamps 屬性設(shè)為 false即可。

取出所有模型數(shù)據(jù)

$users = User::all();

根據(jù)主鍵取出一條數(shù)據(jù)

$user = User::find(1);
var_dump($user->name);

提示: 所有查詢構(gòu)造器里的方法,查詢 Eloquent 模型時(shí)也可以使用。

根據(jù)主鍵取出一條數(shù)據(jù)或拋出異常

有時(shí), 您可能想要在找不到模型數(shù)據(jù)時(shí)拋出異常,通過 firstOrFail 方法。

$model = User::findOrFail(1);
$model = User::where('votes', '>', 100)->firstOrFail();

Doing this will let you catch the exception so you can log and display an error page as necessary. To catch the ModelNotFoundException, add some logic to your app/Exceptions/Handler.php file.

use Illuminate\Database\Eloquent\ModelNotFoundException;

class Handler extends ExceptionHandler {

    public function render($request, Exception $e)
    {
        if ($e instanceof ModelNotFoundException)
        {
            // Custom logic for model not found...
        }

        return parent::render($request, $e);
    }

}

Eloquent 模型結(jié)合查詢語法

$users = User::where('votes', '>', 100)->take(10)->get();

foreach ($users as $user)
{
    var_dump($user->name);
}

Eloquent 聚合查詢

當(dāng)然,您也可以使用查詢構(gòu)造器的聚合查詢方法。

$count = User::where('votes', '>', 100)->count();

如果沒辦法使用流暢接口產(chǎn)生出查詢語句,也可以使用 whereRaw 方法:

$users = User::whereRaw('age > ? and votes = 100', [25])->get();

拆分查詢

如果您要處理非常多(數(shù)千條)Eloquent 查詢結(jié)果,使用 chunk 方法可以讓您順利工作而不會(huì)消耗大量?jī)?nèi)存:

User::chunk(200, function($users)
{
    foreach ($users as $user)
    {
        //
    }
});

傳到方法里的第一個(gè)參數(shù)表示每次「拆分」要取出的數(shù)據(jù)數(shù)量。第二個(gè)參數(shù)的閉合函數(shù)會(huì)在每次取出數(shù)據(jù)時(shí)被調(diào)用。

指定查詢時(shí)連接數(shù)據(jù)庫

您也可以指定在執(zhí)行 Eloquent 查詢時(shí)要使用哪個(gè)數(shù)據(jù)庫連接。只要使用 on 方法:

$user = User::on('connection-name')->find(1);

如果您在使用 讀取 / 寫入連接, 您可以通過如下命令來強(qiáng)制查詢使用 寫入 連接:

$user = User::onWriteConnection()->find(1);
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)