laravel使用具有特定角色的get()

时间:2018-07-18 22:49:41

标签: php laravel

6个项目 有用户模型,这是用户模型中的一种方法

// Read in the config file and add the lines to a list
List<string> accountDetails = File.ReadAllLines(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "account.config")).ToList();

ReportExecutionService myReportExecutionService = new ReportExecutionService();

// Add the credentials
// accountDetails[0] is the username, accountDetails[1] is the password
myReportExecutionService.Credentials = new NetworkCredential(accountDetails[0], accountDetails[1]); 

当我在laravel中使用get()时,一切工作正常

public function setPasswordAttribute($password)
{
    $this->attributes['password'] = bcrypt($password);
}

它返回所有用户。 我的问题是,有没有一种方法可以在模型中编写可以返回条件的用户,而不是所有用户的方法, 像这样

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 } 谢谢

1 个答案:

答案 0 :(得分:5)

您可能正在寻找范围。

https://laravel.com/docs/5.6/eloquent#local-scopes

从文档中

  

本地作用域使您可以定义常见的约束集,可以轻松地在整个应用程序中重复使用这些约束

示例:

public function scopePopular($query)
{
    return $query->where('votes', '>', 100);
}

然后用作

SomeModel::popular()->get();