Max100
1 week ago

Using a lookup table twice in one query

Posted 1 week ago by Max100

I'm new to laravel and have run into some problems.

I need to use the same lookup table twice. This is a simplified example of the issue:

Say I have two tables: users and assignments

Users structure id username

Assignments structure: id description - string user1 - unsigned user2 - unsigned user_id - unsigned (which identifies the person creating the assignment)

Users model: class User extends Model { public function assignments() {

	return $this->hasMany('App\Assignment');
}

}

Assignment model: class Assignment extends Model { public function user() {

	return $this->belongsTo('App\User');
}

}

I want to list all of the assignments assigned by one user.

In the AssignmentController, in the index function I pass in the $user_id and then find all of the assignments created by that user:

public function index($user_id) { $assignments = Assignment::whereId($user_id)->all(); return view("assignment_index", ['assignments' => $assignments]); }

But I also need to retrieve the usernames of assignments.user1 and assignments.user2 to pass to the view.

After trying to do this with relationships, I gave up and decided to just have a query pull everything at once. The query works in HeidiSQL (db app), but I can not seem to translate it into a form that laravel will accept.

Here's the sql query I was trying to run:

SELECT assignments.*, usr1.username AS u1, usr2.username AS u2 FROM assignments left join users AS usr1 on assignments.user1 = usr1.id left join users AS usr2 on assignments.user2 = usr2.id

Does anyone know how I can get this query to run in laravel query builder or eloquent? Or, is there a better way to do this using additional relationships?

Any advice is greatly appreciated.

Please sign in or create an account to participate in this conversation.