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();