joining 3 tables in laravel using DB with similar column names - laravel

I have three 3 tables in my database user_projectswith columns
project_id,
user_id,
role
project_invitations with columns
project_id,
email,
role
and finally users
id,
email
I want to join the three tables using the laravel query builder so that I can get
userid, role, email, invited_user
null member test#gmail.com true
1 owner test123#gmail.com false
2 member test12#gmail.com true
So far I got the following data
[
{
"email":"test#sharklasers.com",
"id":2,
"role":"owner",
"invitedEmail":"test#gmail.com",
"invitedRole":"member"
},
{
"email":"test#sharklasers.com",
"id":2,
"role":"owner",
"invitedEmail":"safda#gmail.com",
"invitedRole":"member"
}
]
using the following query
DB::table('user_projects')
->join('users', 'user_projects.user_id', '=', 'users.id')
->join('project_invitations', 'project_invitations.project_id','=','user_projects.project_id')
->where('user_projects.project_id', '=', $projectId)
->select('users.email', 'users.id', 'user_projects.role', 'project_invitations.email as invitedEmail','project_invitations.role as invitedRole')
->get();

You need to use outer joins to get all records even if there is not a join for the record.
DB::table('user_projects')
->join('users', 'user_projects.user_id', '=', 'users.id', 'outer')
->join('project_invitations', 'project_invitations.project_id','=','user_projects.project_id', 'outer')
->where('user_projects.project_id', '=', $projectId)
->select('users.email', 'users.id', 'user_projects.role', 'project_invitations.email as invitedEmail','project_invitations.role as invitedRole')
->get();

Related

Using Laravel Query Builder, how to join tables from two different databases

I have two different tables in sql server database on the same host that I need to join together in a query.
I would like to use the laravel QueryBuilder to do so.
I've tried so far:
return DB::table('users')
->select([
'users.id',
'Resources.FirstName'
])
->join('Resources.dbo.ID', 'Resources.UserID', '=', 'users.id');
It results in the following error: General error: 1 near ".": syntax error (SQL: select "users"."id", "Resources"."FirstName" from "users" inner join "Resources"."dbo"."ID" on "Resources"."ID" = "users"."id")
If I copy the query in my dabatase script editor and run it, it runs correctly and give the expected result.
I have also tried this
return DB::table('users')
->select([
'users.id',
'Resources.FirstName'
])
->join(DB::raw('Resources.dbo.ID'), 'Resources.UserID', '=', 'users.id');
return DB::table('users')
->select([
'users.id',
'Resources.FirstName'
])
->join(DB::raw('Resources.ID'), 'Resources.UserID', '=', 'users.id');
->join('Resources', function($q) {
$q->connection('tcollect')->on('Resources.ID', '=', 'users.id');
});
Is there a way to achieve this?
Please try that
DB::table('Database1.Resources as dt1')-> join('Database2.users as dt2', 'dt2.id', '=', 'dt1.UserID')->select(['dt1.*','dt2.*'])->get();

Laravel Join returns empty array

$users = DB::table('users')
->join('course', 'users.id', '=', 'course.courseId')
->join('skills', 'users.id', '=', 'skills.id')
->join('subjects', 'users.id', '=', 'subjects.id')
->get();
dd($users);
This gives me an empty result like this- items: []. I would like to join the 4 tables - users, course, skills & subjects and fetch all the data in all the 4 tables. users table has the id column(PK) named as id, course table has the id column(PK) named as courseId, skills table has its id column(PK) named as id & subjects table also has the id column(PK) named as id. The PK of all 4 tables is of the same data type biginteger. How to solve this?
Using the relations to get all the data:
The User::class has three relation methods hasMany() to the other classes (Course::class, Skill::class and Subject::class)
$users = User::with(['courses', 'skills', 'subjects'])->get();

Sort results where "seen" matches 2

I have a table for stories with fields id, user_id, file_name, seen (1-2)
Stories: id, user_id, file_name, seen
I would like to create a list that takes all the stories but with a primary order where seen corresponds to 2 (still to be seen then)
I have this simple query as a test, what should I do?
$users = App\Models\User::whereHas('stories', function ($query) {
})->get();
You can try next:
$users = App\Models\User::whereHas('stories')->with(['stories' => function($query) {
$query->orderBy(DB::raw('stories.seen=2'), 'desc')
}])->get();
Or
$users = App\Models\User::whereHas('stories')
->select('*')
->join('stories', 'stories.user_id', '=', 'users.id')
->orderBy(DB::raw('stories.seen=2'), 'desc')
->get();

How to fetch data from multiple table according to id by using query builder in laravel

How to fetch data from multiple table according to id by using query builder in Laravel?
example:
I have three tables such as student,parent and teacher.Now I want to fetch data from this three tables(student,parent and teacher) according to id for editing.So how can I do that?
see bellow codes please
public function edit($id)
{
$values=DB::table("student")->find($id);
$values=DB::table("parent")->find($id);
$values=DB::table("teacher")->find($id);
return view("info", compact("values"));
}
You probably want to fetch data according to id that you have. Of course that other tables need to have foreign keys of that table>
Here is laravel documentation for joins:
https://laravel.com/docs/5.8/queries#joins
and here is example code from docs:
$users = DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.*', 'contacts.phone', 'orders.price')
->get();

Laravel distinct on join results not working in query builder

I have a posts table that has join query with 4 other tables. 3 of them are one to one relations but the 4th is one to many. I want the query to return only 1 row for each post. What i am trying so far is like this-
$query = DB::table('posts')
->select('posts.*',
'subcategories.subcategory_title_en',
'subcategories.subcategory_title_bn',
'categories.category_title_en',
'categories.category_title_bn',
'users.*',
'postimages.postimage_thumbnail'
)
->join('subcategories', 'subcategories.subcategory_id', '=', 'posts.subcategory_id')
->join('categories', 'categories.category_id', '=', 'subcategories.parent_category_id')
->join('users', 'users.id', '=', 'posts.user_id')
->join('postimages', 'postimages.post_id', '=', 'posts.post_id');
$query->groupBy('posts.post_id');
echo $query->count();
exit();
I have currently 50 posts in database, but the query returns all rows for each postimages, more than 1 row for each post that is. I thought distinct would only show each post_id once? What am i missing here?
I would prefer if someone tells me how to do this with query builder. As this will have a lot of searching on different columns and i want it to be as fast as possible.
This is a simpler version -
$query = DB::table('posts')
->select('posts.*','postimages.postimage_thumbnail')
->join('postimages', 'postimages.post_id', '=', 'posts.post_id')
->groupBy('posts.post_id');
echo $query->count();
exit();
The strange thing is the SQL query that is shown by laravel " select posts.*, postimages.postimage_thumbnail from posts inner join postimages on postimages.post_id = posts.post_id group by posts.post_id" works fine in mysql
You should use groupby
Try this code
$query = DB::table('posts')
->select('posts.*',
'subcategories.subcategory_title_en',
'subcategories.subcategory_title_bn',
'categories.category_title_en',
'categories.category_title_bn',
'users.*',
'postimages.postimage_thumbnail'
)
->join('subcategories', 'subcategories.subcategory_id', '=', 'posts.subcategory_id')
->join('categories', 'categories.category_id', '=', 'subcategories.parent_category_id')
->join('users', 'users.id', '=', 'posts.user_id')
->join('postimages', 'postimages.post_id', '=', 'posts.post_id')->groupBy('posts.post_id');
In config/database.php at "mysql" change : 'strict' => true, to false

Resources