samedi 12 décembre 2015

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
  • Timesheet can have many rows

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. 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.

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()

Does anyone know how I achieve this?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire