Multiple selects in laravel 6.0 - php

0, I have this code that works perfectly
$data = DB::table('incidencias')
->join('clientes_incid', 'clientes_incid.rif', '=', 'incidencias.rif')
->select(DB::raw('count(*) as gold, cat_cliente'))->where('cat_cliente', '=','Gold')
->groupBy('cat_cliente')
->get();
I want to make another select but with another condition, I tried with this but doesn't work
$data = DB::table('incidencias')
->join('clientes_incid', 'clientes_incid.rif', '=', 'incidencias.rif')
->select(DB::raw('count(*) as gold, cat_cliente'))->where('cat_cliente', '=','Gold')
->select(DB::raw('count(*) as silver, cat_cliente'))->where('cat_cliente', '=','Silver')
->groupBy('cat_cliente')
->get();
Can somebody help me?

Group By cat_cliente, this will count gold, count silver..., in each records.
DB::table('incidencias')
->join('clientes_incid', 'clientes_incid.rif', '=', 'incidencias.rif')
->select(DB::raw('count(incidencias.id) as count'), cat_cliente)
->whereIn('cat_cliente', ['Gold', 'Silver'])
->groupBy('cat_cliente')
->get();
output =>
-----------------
count | cat_cliente
------------------
10 | Gold
------------------
3 | Siliver
-----------------
You want to put them in one record, I think you can get it out and display it by loop.
However, if you really want to get it in query, try this:
$gold_query = DB::table('incidencias')
->join('clientes_incid', 'clientes_incid.rif', '=', 'incidencias.rif')
->where('cat_cliente', 'Gold')
->selectRaw('COUNT(incidencias.id) AS gold', '0 AS silver');
$silver_query = DB::table('incidencias')
->join('clientes_incid', 'clientes_incid.rif', '=', 'incidencias.rif')
->where('cat_cliente', 'Silver')
->selectRaw('0 AS gold, count(incidencias.id) AS silver');
$gold_silver = $gold_query->unionAll($silver_query);
DB::table(DB::raw("({$gold_silver->toSql()}) AS gs"))
->mergeBindings($gold_silver)
->selectRaw('SUM(gold) AS gold, SUM(silver) AS silver')
->get()
Output =>
----------------
gold | silver |
-----------------
10 | 3 |
----------------

Related

Get the count of a specific column with join query in Laravel

I have 2 tables, products and stocks. Each product has a stock record foreign key product_id in the stocks table. Each stock record has a quantity column.
Fields in the stocks table look like,
id | product_id | color_id | quantity
In brief: 1 product can have many stock records. I'm trying to get the product and its total count in the quantity column of stock records. Imagine product A (product id is 1) has 3 stock records in the stocks table like this,
id | product_id | color_id | quantity
1 | 1 | 3 | 10
2 | 1 | 4 | 20
3 | 1 | 2 | 40
Here for product A the total of quantity column in the stocks table is 10 + 20 + 40 = 70. I'm expecting to return this 70 and the product record.
Here is my code. I have no idea how to get that,
return DB::table('products')
->join('stocks', 'products.id', '=', 'stocks.product_id')
->paginate(5);
If your joins are correct use sum() with groupBy() clause
->select(DB::raw("SUM(stocks.quantity) as stocks_quantity"))
->groupBy('stocks.product_id') # or ->groupBy('products.id')
DB::table('products')
->join('stocks', 'products.id', '=', 'stocks.product_id')
->select(DB::raw("SUM(stocks.quantity) as stocks_quantity"))
->groupBy('products.id') #or groupBy('stocks.product_id')
->paginate(5);
Edit 01
DB::table('products')
->join('stocks', 'products.id', '=', 'stocks.product_id')
->select('products.*')
->selectRaw("SUM(stocks.quantity) as stocks_quantity")
->groupBy('stocks.product_id')
->get(5);
Edit 02
add 'products.id' in select
DB::table('products')
->leftjoin('stocks', 'products.id', '=', 'stocks.product_id')
->select('products.id','products.*')
->selectRaw("SUM(stocks.quantity) as stocks_quantity")
->groupBy('products.id')
->get(5);

MySQL Display results using foreign key on PHP

I have a table of USER and PORTFOLIO where I wish to display the user's name and the portfolio title, however the name is only retrievable using USER ID and I'm not sure how to get the information across on PHP to reach the other DB table.
USER
id | user_fname | user_lname
01 | John | Smith
02 | Katherine | Blair
PORTFOLIO
id | portfolio_title | portfolio_user_id
19 | ClassRoom | 02
20 | RemoteIsland | 02
21 | MilkTown | 01
Right now in my PHP file,
if( $request->has('s_c'))
{
$categoryid = $request->s_c;
$results = DB::table('portfolio')
->leftJoin('portfolio_images', 'portfolio.id', 'portfolio_images.p_portfolio_id')
->where('portfolio_user_id', 'like', "%".$search_text."%")
->orwhere('portfolio_title', 'like', "%".$search_text."%")
->groupBy('portfolio.id')
->orderBy('portfolio.portfolio_added_date', 'DESC')
->paginate(12);
if($categoryid != '')
$results = $results->where('portfolio_category', $categoryid);
}
else
{
$results = DB::table('portfolio')
->leftJoin('portfolio_images', 'portfolio.id', 'portfolio_images.p_portfolio_id')
->where('portfolio_user_id', 'like', "%".$search_text."%")
->orwhere('portfolio_title', 'like', "%".$search_text."%")
->groupBy('portfolio.id')
->orderBy('portfolio.portfolio_added_date', 'DESC')
->paginate(12);
}
return view('./frontend/portfoliotest', [
'categories' => $categories,
'results' => $results
]);
Which will display it such as
02 ClassRoom
02 RemoteIsland
01 MilkTown
But I want it to reach into the user table as well to get
Katherine Blair ClassRoom
Katherine Blair RemoteIsland
John Smith MilkTown
I'm using $result to display the information from PORTFOLIO table, but how can I get the display of fname and lname of the user instead of it's ID
You should join users table and select the attributes that you need.
You can add this piece of code to the queries:
->join('users', 'users.id', '=', 'portfolio.portfolio_user_id')
->select('users.*', 'portfolio.portfolio_title')
As the select method suggests, the results are user_fname, user_lname, portfolio_title

Laravel join with LIKE CONCAT

Laravel 5.1.11
I have a simple search in my shop:
public function search($request $request)
{
return Catalog::where('title', 'like', '%'.$request->searchQuery.'%')
->orderBy('id', 'desc')
->paginate(50);
}
This is worked!
But people are looking for goods so: Pump BOSCH. And search result is null.
Because I changed my select:
public function search($request $request)
{
$searchQ = preg_split('/\s+/', $request->searchQuery, -1, PREG_SPLIT_NO_EMPTY);
return Catalog::where(function ($q) use ($searchQ) {
foreach ($searchQ as $value) {
$q->orWhere('title', 'like', "%{$value}%");
}
})
->orderBy('id', 'desc')
->paginate(50);
}
And this is worked), and show all Pumps!
But i want show only one Pump bosch.
My DB table manufactories:
| id | title |
| :--: | :----- |
| 1 | AlKO |
| 2 | BOSCH |
AND catalogs, where m_id is id from table manufactory:
| id | m_id | title | url |
| :--: | :---: | :---- | :--------- |
| 1 | 1 | pump | pump-alko |
| 2 | 2 | pump | pump-bosch |
How do I change the MySQL search query (adding LEFT JOIN and CONCAT) to find Pump bosch?
To make it look like this: CONCAT('catalogs.title', ' ', 'manufactories.title') LIKE '%'.$request->searchQuery.'%'
You can do simply like this,
$data = DB::table('manufactories')
->join('catalogs','manufactories.id','=','catalogs.m_id')
->select('manufactories.title','catalogs.title')
->where(DB::raw('CONCAT(manufactories.title," ",catalogs.title)'), 'like',"%{$value}%")
->get();
I hope it helps,
You can use the Query Builder to do joins e.g.
DB::table('catalogs')
->select('catalogs.*')
->join('manufactories', 'catalogs.m_id', '=', 'manufactories.id', 'left')
->where(function($q) use ($searchQ) {
foreach ($searchQ as $value) {
$q->orWhere('manufactories.title', 'like', "%{$value}%");
$q->orWhere('catalogs.title', 'like', "%{$value}%");
}
})
->get();

How to get the max ID in a Join Query in Laravel 5 (Integrity constraint violation:)

My query is like this:
$deals=DB::table('leadsheet')
->join('Deal', 'leadsheet.leadcode', '=', 'Deal.leadcode')
->join('benefits', 'leadsheet.leadcode', '=', 'benefits.leadcode')
->join('delegatedealinfo', 'leadsheet.leadcode', '=', 'delegatedealinfo.leadcode')
->join('vipbooking', 'leadsheet.leadcode', '=', 'vipbooking.leadcode')
->where('id', DB::raw("(select max(`id`) from vipbooking)"))
->where('leadsheet.leadcat', '=','Delegates')
->get();
So I have following tables:
1.leadsheet
-- leadcode
-- leadcat
2.Deal
-- leadcode
3.benefits
-- leadcode
4.delegatedealinfo
-- leadcode
5.vipbooking
-- leadcode
What I'm trying to do is to get all the maximum id of vipbooking form where leadcode is same as all the leadcode FROM leadsheet WHERE leadsheet.leadcat=Delegates
My only problem is MAX ID for vipbooking form is not working
Can any one one help me out
UPDATE1
after applying the solution provided by #anant
Error
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select * from `leadsheet` inner join `Deal` on `leadsheet`.`leadcode` = `Deal`.`leadcode` inner join `benefits` on `leadsheet`.`leadcode` = `benefits`.`leadcode` inner join `delegatedealinfo` on `leadsheet`.`leadcode` = `delegatedealinfo`.`leadcode` inner join `vipbooking` on `leadsheet`.`leadcode` = `vipbooking`.`leadcode` where `id` = (select MAX(id) AS vipid from vipbooking) and `leadsheet`.`leadcat` = Delegates)
Rephrasing Question
I want to get the details of the vipbooking form for a Deal of a Delegate user , we can find if a Deal is Vendor or Delegate from Leadsheet table
Leadsheet
id | leadcode | leadcat
1 | DL2016012| Delegates
2 | DL2016013| Delegates
3 | VL2016001| Vendors
4 | VL2016002| Vendors
Deals
id | leadcode | DealAmount
1 | DL2016012| 123
2 | VL2016002| 1000
2 | DL2016013| 1200
vipbooking
id | leadcode | date | bookingtxt
1 | DL2016012| 20-04-2016| xxx
2 | DL2016012| 20-04-2016| dddd
3 | VL2016012| 21-04-2016| ppp
4 | DL2016013| 20-04-2016| xxx
5 | DL2016013| 22-04-2016| dddd
So my Out put should have
2 123 | Delegates| DL2016012| 20-04-2016| dddd
5 1200| Delegates| DL2016013| 22-04-2016| dddd
Thanks
You can try with the two queries.
$vipBookingMaxId = DB::table('vipbooking')
->select(DB::raw("MAX(`id`) AS maxId"))
->get();
$maxId = (null != $vipBookingMaxId) ? $vipBookingMaxId->maxId : 0;
$dealsQuery = DB::table('leadsheet')
->join('Deal', 'leadsheet.leadcode', '=', 'Deal.leadcode')
->join('benefits', 'leadsheet.leadcode', '=', 'benefits.leadcode')
->join('delegatedealinfo', 'leadsheet.leadcode', '=', 'delegatedealinfo.leadcode')
->join('vipbooking', 'leadsheet.leadcode', '=', 'vipbooking.leadcode');
if ($maxId) {
$dealsQuery->where('id', $vipBookingMaxId->maxId);
}
$deals = $dealsQuery->where('leadsheet.leadcat', '=', 'Delegates')->get();
I hope it will help you.
Try this
$deals=DB::table('leadsheet')
->join('Deal', 'leadsheet.leadcode', '=', 'Deal.leadcode')
->join('benefits', 'leadsheet.leadcode', '=', 'benefits.leadcode')
->join('delegatedealinfo', 'leadsheet.leadcode', '=', 'delegatedealinfo.leadcode')
->join('vipbooking', 'leadsheet.leadcode', '=', 'vipbooking.leadcode')
->where('leadsheet.id', DB::raw("(select max(`id`) from vipbooking)"))
->where('leadsheet.leadcat', '=','Delegates')
->get();
added leadsheet.id

Laravel join query using Laravel eloquent

i have two tables 'users' and 'projects'
Table users
-----------------------------------
user_id | name | email | password |
-----------------------------------
1 |name1 |email1 | password1|
-----------------------------------
2 |name2 |email2 | password2|
Table projects
project_id |user_id | name |
--------------------------------------
1 | 1 | project_name1 |
-----------------------------------
2 | 1 | project_name2 |
There is no relation between these two tables but user_id in projects are the id from user table.
Normal Query
SELECT a.user_id,a.name AS username,b.name AS project_name FROM users a LEFT JOIN projects b ON a.user_id=b.user_id;
I want the same query execution in laravel eloquent.
Have searched in google got some idea about "with" function but not able to get the output.
Thanks.
This is the way you should use Eloquent:
create User.php
<?php
class User extends Eloquent
{
public function projects()
{
return $this->hasMany('Project');
}
}
create Project.php
<?php
class Project extends Eloquent
{
}
On controller, write this to get all users, with related projects inserted inside each users:
$users = User::with('projects')->all();
foreach($users as $user)
{
$project_of_this_user = $user->projects;
}
You can simply do as following,
DB::table('users')
->join('projects =', 'users.id', '=', 'posts.user_id')
->select('*')
->get();
For more details you can refer laravel Docs
This should be what you need:
DB::table('users')
->join('projects', 'projects.user_id', '=', 'users.user_id')
->select('users.user_id', 'users.name as username', 'projects.name as project_name')
->get();
I think, this one helps you out
DB::table('users')
->leftJoin('projects', 'users.user_id', '=', 'projects.user_id')
->select('users.user_id', 'users.name as username', 'projects.name as project_name')
->get();

Categories