class User extends Eloquent {}
注意: 表名將默認爲:類名的複數形式並小寫。主鍵將默認爲: id
。數據庫
protected $table = 'my_users';
protected $primaryKey = 'not_id';
protected $incrementing = false;
protected $timestamps = false;
注意 在默認狀況下須要在表中定義 updated_at
和 created_at
字段。若是不但願它們被自動維護,請在模型中設置 $timestamps
屬性爲 false
。數組
protected $softDelete = true;
protected $connection = 'another';
User::on('connection-name')->find(1);
User::all(); // 推薦使用,語義化 User::get();
User::find(1);
User::first();
User::findOrFail(1); User::where('votes', '>', 100)->firstOrFail();
註冊錯誤處理器,請監聽 ModelNotFoundException:安全
use Illuminate\Database\Eloquent\ModelNotFoundException; App::error(function(ModelNotFoundException $e) { return Response::make('Not Found', 404); });
User::all(array('url')); User::get(array('url')); User::find(1, array('url')); User::find(1)->pluck('url'); User::first(array('url')); User::first()->pluck('url');
User::lists('url');
能夠經過lists的第二個參數爲返回的數組自定義鍵名:函數
User::lists('url', 'id');
User::where('votes', '>', 100)->take(10)->get();
User::where('votes', '>', 100)->count();
User::whereRaw('age > ? and votes = 100', array(25))->get();
User::whereRaw('age > ? and votes = 100', array(25))->distinct()->get();
$user = new User; $user->name = 'John'; $user->save();
protected $fillable = array();
protected $guarded = array();
protected $guarded = array('*');
// 常規方法 User::create(array('name' => 'John')); // 若不存在則建立 User::firstOrCreate(array('name' => 'John')); // 若不存在則建立,且容許你在 save 以前作其它操做 User::firstOrNew(array('name' => 'John'))->save();
$user = User::find(1); $user->email = 'john@foo.com'; $user->save();
$user = User::whereRaw(" name = ? ", array('john'))->get(); $user->push(array('email' => 'john@foo.com')); $user->save();
$user->touch();
$user = User::find(1); $user->delete(); $affectedRows = User::where('votes', '>', 100)->delete();
User::destroy(1); User::destroy(array(1, 2, 3)); User::destroy(1, 2, 3);
模型中開啓軟刪除:url
protected $softDelete = true;
表中必須添加 deleted_at
字段:rest
$table->softDeletes(); // 詳見結構生成器 Schema
與刪除相同,只是數據並不是真的刪除,而是經過 deleted_at
字段標記。code
User::withTrashed()->where('account_id', 1)->get();
User::onlyTrashed()->where('account_id', 1)->get();
if ($user->trashed())
$user->restore();
$user->forceDelete();
針對系統的自動維護三字段: created_at
updated_at
deleted_at
orm
class User extends Eloquent { protected function getDateFormat() { return 'U'; } }
public function scopePopular($query) { return $query->where('votes', '>', 100); }
User::popular()->orderBy('created_at')->get();
添加參數到您的範圍函數:rem
public function scopeOfType($query, $type) { return $query->whereType($type); }
而後在範圍函數調用中傳遞參數:get
User::ofType('member')->get();