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','students.id',
'=','asignaciones.id_student')
->join('users as teachers','teachers.id',
'=','asignaciones.id_teacher')
->select('asignaciones.id','students.name',
'teachers.name')->get();
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:
php
$posts = DB::table('posts')
->join('users', 'posts.user_id', '=', 'users.id')
->select('posts.*', 'users.name')
->get();
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
4 of 5 based on 8514 votesComments