作者:mobiledu2502920413 | 来源:互联网 | 2022-12-10 11:52
6个项目并且有用户模型,这是用户模型中的一种方法
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
当我在这样的laravel中使用get()时,一切正常
User::get();
它返回所有用户.我的问题是,有没有办法在模型中编写方法,可以返回有条件的用户,而不是像这样的所有用户
public function setRoleToGetData()
{
$user = Auth::user()->getSex // getSex is method in the model
if($user == 1)
return users in the whole program like this
User::where('user_sex','=',1)->get();
else
// return the reverse
}
我不想写where('user_sex','=',1) in every time i want to get users
感谢
1> Luiz..:
您可能正在寻找范围.
https://laravel.com/docs/5.6/eloquent#local-scopes
来自文档:
本地范围允许您定义可在整个应用程序中轻松重用的常见约束集
例:
public function scopePopular($query)
{
return $query->where('votes', '>', 100);
}
然后用作
SomeModel::popular()->get();