SQL query in QueryBuilder - laravel

My query works fine in phpMyadmin, but I can't convert this sql query to querybuilder . i have problems with "distinct" any help please ?
SELECT sum(`users`.`ca`), sum(distinct `sales`.`amount`), `users`.`id` , `users`.`email`
FROM `sales`,`users`
WHERE `sales`.`user_id`=`users`.`id`
GROUP BY `user_id`
In my querybuilder
$results = DB::table('users')
->select('users.id', 'users.email', DB::raw('SUM(users.ca)'), DB::raw('SUM(sales.amount)'))
->join('sales', 'users.id', '=', 'sales.user_id')
->groupBy('users.id')
->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 db query from subquery (mergebindings)

I have DB query like this :
$visitor = DB::table('visitor_anonymous')
->join('users', 'visitor_anonymous.host', '=', 'users.host')
->whereBetween('visitor_anonymous.created_at', [$startDate, $endDate])
->select(DB::raw('DATE(visitor_anonymous.created_at) AS date, COUNT(visitor_anonymous.host) AS visitor'))
->groupBy(DB::raw("DATE(visitor_anonymous.created_at)"));
$session = DB::table('visitor_anonymous')
->join('visitor_anonymous_pageviews', 'visitor_anonymous.session_id', '=', 'visitor_anonymous_pageviews.session_id')
->join('users', 'visitor_anonymous.host', '=', 'users.host')
->whereBetween('visitor_anonymous_pageviews.created_at', [$startDate, $endDate])
->select(DB::raw('DATE(visitor_anonymous_pageviews.created_at) AS date, COUNT(visitor_anonymous_pageviews.session_id) AS session'))
->groupBy(DB::raw("DATE(visitor_anonymous_pageviews.created_at), visitor_anonymous.session_id"));
$pageview = DB::table('visitor_anonymous')
->join('visitor_anonymous_pageviews', 'visitor_anonymous.session_id', '=', 'visitor_anonymous_pageviews.session_id')
->join('users', 'visitor_anonymous.host', '=', 'users.host')
->whereBetween('visitor_anonymous_pageviews.created_at', [$startDate, $endDate])
->select(DB::raw('DATE(visitor_anonymous_pageviews.created_at) AS date, sum(visitor_anonymous_pageviews.count) AS pageview'))
->groupBy(DB::raw("DATE(visitor_anonymous_pageviews.created_at)"));
Hope result like this but didn't work. How to join subquery like this ?
$table = DB::table( DB::raw("({$visitor->toSql()}) as v"))
->leftJoin(DB::raw("({$session->toSql()}) as s"), 'v.date','=','s.date')
->leftJoin(DB::raw("({$pageview->toSql()}) as p"), 'v.date','=','p.date')
->select(DB::raw('v.date, sum(visitor) AS visitor, sum(session) AS session, sum(pageview) AS pageview'))
->groupBy(DB::raw("v.date"))
->mergeBindings($visitor);
Please tell me, solution. Thanks

How to make query at laravel

I have sql like this
SELECT no_po FROM tpo_suppheader WHERE no_po not in (
SELECT no_po FROM tpo_supp_stok ).
How to code at laravel?
$datas = DB::table ('tpo_suppheader')
->join('tpo_suppdetil', 'tpo_suppheader.no_po', '=', 'tpo_suppdetil.no_po')
->join('tmsupplier', 'tpo_suppheader.suppid', '=', 'tmsupplier.id')
->select('tpo_suppheader.*', 'tpo_suppdetil.*', 'tmsupplier.nama_supp')
->where('tpo_suppheader.no_po','like',"%".$var_cari."%")
->whereNotIn('no_po', $data_dtl)
->get();
$datas = DB::table ('tpo_suppheader')
->join('tpo_suppdetil', 'tpo_suppheader.no_po', '=', 'tpo_suppdetil.no_po')
->join('tmsupplier', 'tpo_suppheader.suppid', '=', 'tmsupplier.id')
->select('tpo_suppheader.*', 'tpo_suppdetil.*', 'tmsupplier.nama_supp')
->where('tpo_suppheader.no_po','like',"%".$var_cari."%")
->whereNotIn('no_po', $data_dtl)
->get();
This will work for every query: use toSql() to know how the builder translates a query.
For example:
dd(DB::table('table1')->...->toSql());
will dump the translated query. Tinker with this until you get the desired result. Using this method of trial and error, I got this:
$query = DB::table('tpo_suppheader')->select('no_po') # SELECT no_po FROM tpo_suppheader
->whereNotIn('no_po', function ($subquery) { # WHERE no_po NOT IN (
$subquery->select('no_po')->from('tpo_supp_stok'); # SELECT no_po FROM tpo_supp_stok
}); # )
dd($query->toSql());
# "select "no_po" from "tpo_suppheader" where "no_po" not in (select "no_po" from "tpo_supp_stok")"
$results = $query->get();

Query builder in Laravel in not working

I have sql query that is working fine in MySQL. I want to get profile id from profiles table using join with user table.
SELECT profiles.profile_id FROM profiles
left JOIN users on profiles.id = users.id where users.id = 1
Laravel Query builder query is
$my_user_id = Auth::user()->id;
$my_id = DB::table('profiles')->select('profiles.profile_id')
->leftjoin('users','users.id' ,'=' ,'profiles.id')
->pluck('profiles.profile_id')
->where('users.id',$my_user_id)
->first();
Call where() before pluck() (select() is not necessary):
$my_id = DB::table('profiles')
->leftJoin('users', 'users.id', '=' , 'profiles.id')
->where('users.id', $my_user_id)
->pluck('profiles.profile_id')
->first();
You can also shorten it with value():
$my_id = DB::table('profiles')
->leftJoin('users', 'users.id', '=' , 'profiles.id')
->where('users.id', $my_user_id)
->value('profiles.profile_id');
You should select the id as well to perform the join :
DB::table('profiles')->select('profiles.profile_id', 'profiles.id')
->leftjoin('users','users.id' ,'=' ,'profiles.id')
->where('users.id',$my_user_id)
->pluck('profiles.profile_id')
->first();

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