John Davidson

php - Query builder in Laravel - 2 foreigns key in a


I have a problem in my project

I'm trying to do a query with the table "Asignaciones", this table save the records for students and teachers asignations. (The teachers can comment the works of students and can see only the students that are asigned) The principal problem is that all the users is on the same table and when i try to return a names just have one.

$asignaciones = DB::table('asignaciones')
->join('users as students','',
->join('users as teachers','',

return $asignaciones;

I need to get two names (Maybe changing the column name like a users table) to show in a table

Thanks for your time and answers! :)

My Answer:
users and another table called posts. In the posts table, I have a column called user_id which is a foreign key referencing the id column in the users table.

I want to retrieve all posts along with the name of the user who created the post. Here is how you can achieve this using Laravel's query builder:

$posts = DB::table('posts')
->join('users', 'posts.user_id', '=', '')
->select('posts.*', '')

In this query, we are using the `join` method to join the posts table with the users table on the user_id column in the posts table and the id column in the users table. We are then selecting all columns from the posts table (`posts.*`) along with the name column from the users table.

This will give you a collection of posts with the name of the user who created each post.

Rate this post

3 of 5 based on 5355 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us