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 = '[email protected]';
$user->save();
$user = User::whereRaw(" name = ? ", array('john'))->get();
$user->push(array('email' => '[email protected]'));
$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);
模型中开启软删除:
protected $softDelete = true;
表中必须添加 deleted_at
字段:
$table->softDeletes(); // 详见结构生成器 Schema
与删除相同,只是数据并非真的删除,而是通过 deleted_at
字段标记。
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
class User extends Eloquent {
protected function getDateFormat()
{
return 'U';
}
}
public function scopePopular($query)
{
return $query->where('votes', '>', 100);
}
User::popular()->orderBy('created_at')->get();
添加参数到您的范围函数:
public function scopeOfType($query, $type)
{
return $query->whereType($type);
}
然后在范围函数调用中传递参数:
User::ofType('member')->get();