如何只检索那些在 laravel4 中通过所需条件的对象及其相关模型?

How to retrieve only those object and its related model which passes the required criteria in laravel4?

我有三个 table:用户、部门和名称

我已经为 'users'、'designations' 和 'departments' table 创建了相应的模型。

table 之间的关系是:

User model

public function department(){
  return $this->belongsTo('Department');
}
public function designation(){
  return $this->belongsTo('Designation');
}

--

Department model

public function users(){
  return $this->hasMany('User');
}

--

Designation model

public function users(){
  return $this->hasMany('User');
}

现在,我将如何查询(以 eloquent 方式)以检索仅属于指定部门(例如,仅 'account' 部门)的所有用户。

我也试过预先加载,但是因为有两个模型要加载,所以比较混乱。

我有如下代码,但现在可以使用了。帮我找出错误

$users = new User;
$users = $users->department()->where('dept_code', '=', 'account')->get();
return View::make('staffs', compact('users'));

您定义与常量的关系。像这样:

用户模型

public function department(){
  return $this->belongsTo('Department');
}

public function accounts_department(){
  return $this->belongsTo('Department')->where('dept_code', 'account');
}

那你就这样用

$all_users = new User;
$all_users = $all_users->department()->get();

$account_only_users = new User;
$account_only_users = $account_only_users ->accounts_department()->get();

这里有两种方法:

1。从Department那边

$department = Department::where('dept_code', 'account')->first();
$users = $department->users;

2。从 User 端使用 whereHas

$users = User::whereHas('department', function($q){
    $q->where('dept_code', 'account');
})->get();

(当然你也可以像$users = new User; $users->where(一样使用它们,但我更喜欢静态调用语法所以我在我的例子中使用它们)