cirlord
cirlord

Reputation: 29

Laravel Scope with join query

What im trying to do is to make this join into a scope function

$workorders =\DB::table('users')->leftjoin('work_orders','users.id','=','work_orders.user_id')->select('users.id','users.name','users.email','users.status','work_orders.cod','work_orders.deadline'->where('users.id','=','1');    
$workorders = $workorders->get();

This is what I've tried with no success...

public function scopeOrders($query){
        return $query->join('work_orders','users.id','=','work_orders.user_id')
        ->select('users.id','users.name','users.email','users.status','work_orders.cod','work_orders.deadline')
        ->where('users.id','=','1');
    }

Expected result using the scope in a query

$usersWO = User::Orders()->get();

Upvotes: 0

Views: 536

Answers (1)

Larry Kagan
Larry Kagan

Reputation: 56

The only difference between $workorders = $workorders->get(); and $usersWO = User::Orders()->get(); is the output format. They both are bug-free.

A dd() on the former outputs a collection of stdClass objects with record values as properties.:

enter image description here

A dd() on the latter outputs a collection of models:

enter image description here

To modify the output of the second to look exactly like the first, you'll have to modify the client code since scopes return collections of models.

$usersWO = User::Orders()->get()->map(function ($user) {
    return (object) $user->getAttributes();
});

Upvotes: 1

Related Questions