Question

I am new to Laravel, Thanks for helping

I had two Eloquent models, Job and User

The Job Model as follows:

<?php
class Job extends Eloquent {

  protected $table = 'tbl_jobs';

  public function User() {
    return $this->belongsTo('User','uid');
  }

  public function scopeWork($query) {
    return $query->where('worktime', '=', 0); 
  }
}

and the User Model is:

<?php

use Illuminate\Auth\UserInterface;

class User extends Eloquent implements UserInterface {
  protected $table = 'tbl_users';

  public function scopeActive($query) {
    return $query->where('status', '=', 'Active'); 
  }
}

The Question is How can I call both models with scope(Active and Work) in one statements? or some thing like

    Job::Work()->with('user')->get();

is that belongsTo is not equal to inner join??

Was it helpful?

Solution

For intersection you need this:

Job::work()     // apply scope on jobs
  ->whereHas('user', function ($q) {
    // apply users scope to get only jobs with active users
    $q->active();

})->with(['users' => function ($q) {
    // apply scope on users' eager loading to load only active 
    $q->active();

})->get();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top