本文重点介绍 Laravel 框架的 Eloquent 基础 知识!
1
|
class
User
extends
Eloquent {}
|
注意: 表名将默认为:类名的复数形式并小写。主键将默认为: id
。
1
|
protected
$table =
'my_users'
;
|
1
|
protected
$primaryKey =
'not_id'
;
|
1
|
protected
$incrementing =
false
;
|
1
|
protected
$timestamps =
false
;
|
注意 在默认情况下需要在表中定义 updated_at
和 created_at
字段。如果不希望它们被自动维护,请在模型中设置 $timestamps
属性为 false
。
1
|
protected
$softDelete =
true
;
|
1
|
protected
$connection =
'another'
;
|
1
|
User::on(
'connection-name'
)->find(
1
);
|
1
2
|
User::all();
// 推荐使用,语义化
User::get();
|
1
|
User::find(
1
);
|
1
|
User::first();
|
1
2
|
User::findOrFail(
1
);
User::where(
'votes'
,
'>'
,
100
)->firstOrFail();
|
注册错误处理器,请监听 ModelNotFoundException:
1
2
3
4
5
|
use Illuminate\Database\Eloquent\ModelNotFoundException;
App::error(function(ModelNotFoundException $e)
{
return
Response::make(
'Not Found'
,
404
);
});
|
1
2
3
4
5
6
|
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'
);
|
1
|
User::lists(
'url'
);
|
可以通过lists的第二个参数为返回的数组自定义键名:
1
|
User::lists(
'url'
,
'id'
);
|
1
|
User::where(
'votes'
,
'>'
,
100
)->take(
10
)->get();
|
1
|
User::where(
'votes'
,
'>'
,
100
)->count();
|
1
|
User::whereRaw(
'age > ? and votes = 100'
, array(
25
))->get();
|
1
|
User::whereRaw(
'age > ? and votes = 100'
, array(
25
))->distinct()->get();
|
1
2
3
|
$user =
new
User;
$user->name =
'John'
;
$user->save();
|
1
|
protected
$fillable = array();
|
1
|
protected
$guarded = array();
|
1
|
protected
$guarded = array(
'*'
);
|
1
2
3
4
5
6
|
// 常规方法
User::create(array(
'name'
=>
'John'
));
// 若不存在则创建
User::firstOrCreate(array(
'name'
=>
'John'
));
// 若不存在则创建,且允许你在 save 之前做其它操作
User::firstOrNew(array(
'name'
=>
'John'
))->save();
|
1
2
3
|
1
2
3
|
$user = User::whereRaw(
" name = ? "
, array(
'john'
))->get();
$user->save();
|
1
|
$user->touch();
|
1
2
3
|
$user = User::find(
1
);
$user->delete();
$affectedRows = User::where(
'votes'
,
'>'
,
100
)->delete();
|
1
2
3
|
User::destroy(
1
);
User::destroy(array(
1
,
2
,
3
));
User::destroy(
1
,
2
,
3
);
|
模型中开启软删除:
1
|
protected
$softDelete =
true
;
|
表中必须添加 deleted_at
字段:
1
|
$table->softDeletes();
// 详见结构生成器 Schema
|
与删除相同,只是数据并非真的删除,而是通过 deleted_at
字段标记。
1
|
User::withTrashed()->where(
'account_id'
,
1
)->get();
|
1
|
User::onlyTrashed()->where(
'account_id'
,
1
)->get();
|
1
|
if
($user->trashed())
|
1
|
$user->restore();
|
1
|
$user->forceDelete();
|
针对系统的自动维护三字段: created_at
updated_at
deleted_at
1
2
3
4
5
6
7
8
|
class
User
extends
Eloquent {
protected
function getDateFormat()
{
return
'U'
;
}
}
|
1
2
3
4
|
public
function scopePopular($query)
{
return
$query->where(
'votes'
,
'>'
,
100
);
}
|
1
|
User::popular()->orderBy(
'created_at'
)->get();
|
添加参数到您的范围函数:
1
2
3
4
|
public
function scopeOfType($query, $type)
{
return
$query->whereType($type);
}
|
然后在范围函数调用中传递参数:
1
|
User::ofType(
'member'
)->get();
|