An eloquent query using a join to retrieve a pivot table and related data

In my controller, I have a request like this:

$userinfos = User::with('skills');
$userinfos->with('positions');
$userinfos=$userinfos->get();

And it works great, in my opinion, I get the position name as follows:

@forelse ($userinfos[0]->positions as $key=>$position)
    {{ $position->name}}
@empty
    No position listed
@endforelse 

I have another way to get company related data:

$positions = \DB::table('positions')
->select(\DB::raw('position_user.id as id, positions.id as position_id, positions.name as position_name, companies.id as company_id, companies.name as company_name, position_user.user_id'))
->join('position_user','position_user.position_id','=','positions.id')
->join('companies','companies.id','=','position_user.company_id')
->join('users','users.id','=','position_user.user_id')
->where('position_user.user_id',$userid)
->get();

And it also works great to get position and company name:

@forelse($positions as $key=>$position)
    {{$position->position_name}} @ {{$position->company_name}}
@empty
    No position listed
@endforelse

I am sure there must be a way to combine the two so that I can get the company name in the first request. I am looking for something like this:

$userinfos = User::with('skills');
$userinfos->with('positions');
$userinfos->whereHas('positions', function($thisQuery) 
{
    $thisQuery->join('companies','companies.id','=','position_user.company_id');
});

$userinfos=$userinfos->get();

Is it possible? Any ideas / direction would be greatly appreciated!

EDIT:

Should I perhaps look at adding Position to my class to include this:

public function users()
{
    return $this->belongsToMany('App\User')->withTimestamps()
    ->withPivot('company_id');
    ->join('companies','companies.id','=','position_user.company_id');
}

If so, how do I access this in the view?

+4
source share
1

, , ​​ UserPosition, newPivot().

class User extends Eloquent {

public function positions() { 
   return $this->belongsToMany('Position')->withPivot('company_id');
}

public function newPivot(Model $parent, array $attributes, $table, $exists) {

if ($parent instanceof Position) {
    return new UserPosition($parent, $attributes, $table, $exists);
}

    return parent::newPivot($parent, $attributes, $table, $exists);
}

}

,

class UserPosition extends  Illuminate\Database\Eloquent\Relations\Pivot { 

    public function company() {
        return $this->belongsTo('Company');
    }
}

- . , ().

$user = User::find(1);
$user->positions()->first()->pivot->company 

, , . . , .

+1

Source: https://habr.com/ru/post/1599432/


All Articles