简体   繁体   English

Laravel 5查询关系模型

[英]Laravel 5 querying relationship models

I am trying to query one of my model relationships in a timesheet system I am building. 我试图在我正在建立的时间表系统中查询我的模型关系之一。 I have the following models setup: 我有以下模型设置:

  • User can have many timesheets and can belong to many employee types User可以有许多时间表,并且可以属于许多员工类型
  • Timesheet can have many rows Timesheet可以有很多行

The models are setup like so: 模型设置如下:

User Model: 用户模型:

<?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();
}

Timesheet Model: 时间表模型:

<?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');
}

My question is, how can I query the User relationship and get timesheets by employee_type . 我的问题是,如何查询用户关系并通过employee_type获取时间表。 This means I need to access timesheet table, then get users associated with the timesheet and then get the users by an employee type that I specify. 这意味着我需要访问timesheet表,然后获取与时间表相关联的用户,然后按我指定的员工类型获取用户。

I have tried the following... 我尝试了以下方法...

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

...but it gives an error... ...但是它给出了一个错误...

Error: 错误:

Call to undefined method Illuminate\\Database\\Query\\Builder::employeeTypes() 调用未定义的方法Illuminate \\ Database \\ Query \\ Builder :: employeeTypes()

Does anyone know how I achieve this? 有谁知道我是怎么做到的?

Timesheets doesn't have that method. 时间表没有该方法。 That method (relationship) exists on User, not Timesheet. 该方法(关系)存在于用户而非时间表上。

You can try something like this and see if it would work. 您可以尝试类似的方法,看看是否可行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM