2
votes

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

1
No, with() is not joining anything. So the question is: do you want to get models intersection (Job scope AND User scope) or get Job in scope, and then add related Users that match scope (or not add if they don't) - the latter may result in Job without users, while first can'tJarek Tkaczyk
Thank you, deczo, I want to get models intersection both Work scope and Active scope, that means I want to get the tbl_jobs.worktime = 0 and tbl_users.status = 'active', how can I do?Geeks

1 Answers

6
votes

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