Laravel 5查询关系模型


Laravel 5 querying relationship models

我正试图在正在构建的时间表系统中查询我的一个模型关系。我有以下模型设置:

  • User可以有许多时间表,并且可以属于许多员工类型
  • Timesheet可以有许多行

模型设置如下:

用户模型:

<?php namespace App'Models'User;
....
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
/**
 * The employee types that belong to the user.
 *
 * @return Object
 */
public function employeeTypes()
{
    return $this->belongsToMany('App'Models'User'EmployeeType')->withTimestamps();
}

时间表模型:

<?php namespace App'Models'Timesheet;
....
class Timesheet extends Model
{    
/**
 * The user that owns the timesheet.
 *
 * @return Object
 */
public function user()
{
    return $this->belongsTo('App'Models'User'User');
}

我的问题是,如何通过employee_type查询用户关系并获取时间表。这意味着我需要访问timesheet表,然后获取与时间表关联的用户,然后根据我指定的员工类型获取用户。

我试过以下。。。

$timesheets->with('user')->whereHas('employeeTypes', function ($query) use ($request) { 
     $query->where('name', 'my_employee_type'); 
});

但它给出了一个错误。。。

错误:

调用未定义的方法Illuminate''Database''Query''Builder::employeeTypes()

有人知道我是如何做到这一点的吗?

时间表没有这个方法。该方法(关系)存在于用户上,而不是时间表上。

你可以试试这样的方法,看看它是否有效。

$timesheets = Timesheet::whereHas('user.employeeTypes', function ($q) {
    $q->where('name', 'something');
})->get();