0

I have 4 tables. Championships, Users, Roles and users_roles.

One user belongs to championship as judge. But I have to select only users who have role 'Judge'.

For this, I created new column in championships table which is called "main_judge" and created new relationship

class Championship extends Model
{
    ...
    public function mainJudge()
    {
        return $this->hasOne('App\User', 'id', 'main_judge');
    }
    ...
}

Then I add to query some code

$query->join('users_roles', 'users.id',  '=', 'users_roles.user_id')
            ->join('roles', 'users_roles.role_id', '=', 'roles.id')
            ->where('roles.alias', '=', 'judge');

when I print query as sql I got (see screen)

http://joxi.ru/a2X45M1Sw0RpE2

and after $query->get() instead of user ID i got a role ID (see screen)

http://joxi.ru/bmoxMaDs3NVoE2

Viktor
  • 1,532
  • 6
  • 22
  • 61

1 Answers1

0

I would suggest using eloquent rather than the query builder as it will remove the need to manually define any joins.

You should just be able to do this:

$championship = Championship::find($id);

$judge = $championship->mainJudge;

If you then dd($judge) you should end up with the appropriate User object.

Spholt
  • 3,724
  • 1
  • 18
  • 29