How to perform this Query on Laravel?
SELECT *
FROM conversion t1
JOIN (SELECT report_id, MAX(id) id
FROM conversion
GROUP BY report_id ) AS t2
ON t1.id = t2.id AND t1.report_id = t2.report_id
I already read in Laravel Documentary and not find an anything,
I already try in SQL and working but I don't know how to perform this Query in Laravel.
Please help to resolve this, Thank You.
I think this is the correct solution for your question:
$subQuery = \DB::table('conversion')
->selectRaw('report_id, MAX(id) id')
->groupBy('report_id')
->toSql();
$data = \DB::table('conversion t1')
->join(\DB::raw('(' . $subQuery . ') as t2'), function ($join) {
$join->on('t1.id', 't2.id')
->on('t1.report_id', 't2.report_id');
}, null, null, '')
->get();
If you want to check the query of this one you can use ->toSql() instead of ->get() in the end.
The output is:
select *
from `conversion t1`
join (
select report_id, MAX(id) as id
from `conversion`
group by `report_id`
) as t2
on `t1`.`id` = `t2`.`id`
and `t1`.`report_id` = `t2`.`report_id`
Didnt have my IDE right now, but it should work this way:
$results = DB::select(DB::raw ('SELECT *
FROM conversion t1
JOIN (SELECT report_id, MAX(id) id
FROM conversion
GROUP BY report_id ) AS t2
ON t1.id = t2.id AND t1.report_id = t2.report_id'));
Related
In Laravel 4.2, I am trying to achieve a query that returns all users, that have all of certain activities. As of now, I have a query that returns all users that have one of many activities:
//$selectedActivities being an array
$userByActivities = User::with('activities')
->whereHas('activities', function($query) use($selectedActivities){
$query->whereIn('id', $selectedActivities);
})->get();
To be more clear: given activities a,b,c. I am looking for all users that have activity a AND b AND c. My query returns all users that have activity a OR b OR c.
Thank you for your help.
EDIT:
The solution offered by lukasgeiter results in following query:
select * from `users` where
(select count(*) from `activities` inner join `activity_user` on `activities`.`id` = `activity_user`.`activity_id` where `activity_user`.`user_id` = `users`.`id` and `id` = '7') >= 1
and (select count(*) from `activities` inner join `activity_user` on `activities`.`id` = `activity_user`.`activity_id` where `activity_user`.`user_id` = `users`.`id` and `id` = '3') >= 1
and (select count(*) from `activities` inner join `activity_user` on `activities`.`id` = `activity_user`.`activity_id` where `activity_user`.`user_id` = `users`.`id` and `id` = '1') >= 1
and (select count(*) from `activities` inner join `activity_user` on `activities`.`id` = `activity_user`.`activity_id` where `activity_user`.`user_id` = `users`.`id` and `id` = '2') >= 1
Whereas the solution offered by Jarek Tkaczyk:
$userByActivities = User::with('activities')
->whereHas('activities', function($query) use($selectedActivities) {
$query->selectRaw('count(distinct id)')->whereIn('id', $selectedActivities);
}, '=', count($selectedActivities))->get();
for a similar request, results in following query:
select * from `users` where (select count(distinct id) from `activities`
inner join `activity_user` on `activities`.`id` = `activity_user`.`activity_id`
where `activity_user`.`user_id` = `users`.`id` and `id` in ('7', '3', '1', '2')) = 4
You'll have to add multiple whereHas for that:
$query = User::with('activities');
foreach($selectedActivities as $activityId){
$query->whereHas('activities', function($q) use ($activityId){
$q->where('id', $activityId);
});
}
$userByActivities = $query->get();
If you are getting Cardinality violation: 1241 Operand should contain 2 column(s) the problem is the nested selectCount adds to the normal select count(*) instead of overriding the existing select, so changing to $query->distinct()->whereIn('id', $selectedActivities); did the trick for me, or changing to $query->select(DB::raw(count(distinct id)))
I have this query in SQL that's working fine:
SELECT tl.*
FROM table1 tl
INNER JOIN table2 tl2
ON tl.id = tl2.other_id
INNER JOIN
(
SELECT other_id, MAX(date) maxDATE
FROM table2
GROUP BY other_id
)
tlv2 ON tl2.other_id = tlv2.other_id AND
tl2.date = tlv2.maxDATE WHERE tl.access=0
ORDER BY tlv2.maxDATE DESC
Now the problem is, I cant seem to figure out how to translate this into the Doctrine query builer.
I have this:
$subquery = $this->getEntityManager()->getRepository(Table2::class)
->createQueryBuilder('tl2')
->select(array('other_id','MAX(date) maxDate'))
->groupBy('other_id')
->getDQL();
$qb = $this->createQueryBuilder('tl');
$qb->select('tl')
->innerJoin(Table2::class,'tl2','WITH','tl.id = tl2.other_id')
->innerJoin("(".$subquery.")",'tlv2','WITH','tl2.date = tlv2.maxDATE')
->where('tl.access = 0')
->orderBy('tlv2.maxDATE','DESC');
but it's giving me the error:
Subquery is not supported here
On the line where I put the $subquery variable.
I cant seem to figure out what I'm doing wrong here. What am I doing wrong?
as mentioned here if you are using the ORM then the mapping will fail, you can only run this without hydration, in case you are using the DBAL only it will work as you expect
If you would go for native query solution and still need a mapped result then you can use \Doctrine\ORM\EntityManager::createNativeQuery with \Doctrine\ORM\Query\ResultSetMapping
$sql = <<<SQL
SELECT tl.*
FROM table1 tl
INNER JOIN table2 tl2
ON tl.id = tl2.other_id
INNER JOIN
(
SELECT other_id, MAX(date) maxDATE
FROM table2
GROUP BY other_id
)
tlv2 ON tl2.other_id = tlv2.other_id AND
tl2.date = tlv2.maxDATE WHERE tl.access=0
ORDER BY tlv2.maxDATE DESC
SQL;
$rsm = new Query\ResultSetMapping();
$rsm->addEntityResult(Entity::class, 'e');
$rsm->addFieldResult('e','id', 'id');
$rsm->addFieldResult('e','date', 'createAt');
$result = $this->entityManager->createNativeQuery($sql, $rsm)->getResult();
I have the following SQL
SELECT C.CUOCODE, C.NAME, COUNT(*) TOTAL_PAYMENT, SUM(P.AMOUNT) TOTAL_AMOUNT
FROM TAX_PAYMENT P
INNER JOIN TAX_CHECKPOINT C ON C.CUOCODE = REGEXP_SUBSTR(P.INVOICEID, 'R....')
WHERE DELETED = 0 AND TO_CHAR(TXTIME,'YYYY-MM-DD') = '2018-04-24'
GROUP BY C.CUOCODE, C.NAME
ORDER BY TOTAL_AMOUNT DESC;
How can i convert to laravel eloquent, i have "Payment" model (table TAX_PAYMENT) with "paymentid" as primary key.
DB::table('TAX_PAYMENT as P')
->select([
'C.CUOCODE',
'C.NAME',
DB::raw('COUNT(*) AS TOTAL_PAYMENT'),
DB::raw('SUM(P.AMOUNT) AS TOTAL_AMOUNT'),
])->Join('TAX_CHECKPOINT C', 'C.CUOCODE', '=', DB::raw('REGEXP_SUBSTR(P.INVOICEID,'R....')'))
->where('DELETED', 0)
->where(DB::raw("TO_CHAR(TXTIME,'YYYY-MM-DD')"), '2018-04-24')
->groupBy('C.CUOCODE')
->groupBy('C.NAME')
->orderBy('TOTAL_AMOUNT', 'desc')
->toSql();
output
SELECT
`C`.`CUOCODE`,
`C`.`NAME`,
COUNT(*) AS TOTAL_PAYMENT,
SUM(P.AMOUNT) AS TOTAL_AMOUNT
FROM
`TAX_PAYMENT` AS `P`
INNER JOIN `TAX_CHECKPOINT C` ON `C`.`CUOCODE` = REGEXP_SUBSTR (P.INVOICEID,"R....")
WHERE
`DELETED` = ?
AND TO_CHAR (TXTIME, 'YYYY-MM-DD') = ?
GROUP BY
`C`.`CUOCODE`,
`C`.`NAME`
ORDER BY
`TOTAL_AMOUNT` DESC
A quick and dirty way would be to use Eloquents select raw like:
$result = DB::select( DB::raw("SELECT C.CUOCODE, C.NAME, COUNT(*)
TOTAL_PAYMENT, SUM(P.AMOUNT) TOTAL_AMOUNT FROM TAX_PAYMENT INNER JOIN
TAX_CHECKPOINT C ON C.CUOCODE
= REGEXP_SUBSTR(P.INVOICEID, 'R....') WHERE DELETED = 0 AND
TO_CHAR(TXTIME,'YYYY-MM-DD') = '2018-04-24' GROUP BY C.CUOCODE,
C.NAME ORDER BY TOTAL_AMOUNT DESC"));
i'm trying to convert this SQl query to QueryBuilder but i can't do it.
SELECT a.id, a.category_name, cat.Count
FROM `categories` a
LEFT OUTER JOIN (
SELECT `categories`.`category_parent` , COUNT(*) AS Count
FROM `categories`
GROUP BY category_parent
)
cat ON a.id = cat.category_parent
WHERE a.category_parent = 1
for example:
DB::table('users')
->join('contacts',DB::raw("a.id = cat.category_parent"),function($query){
$query->select(DB::raw("`categories`.`category_parent` , COUNT( * ) AS Count"))
->from('contacts')
->groupBy('category_parent')
->where(DB::raw("a.category_parent = 1"))
->get();
how to fix this method in laravel. thanks
Try getting the PDO instance to execute your query directly:
$PDO=DB::connection('mysql')->getPdo();
$stmt=$PDO->prepare("
SELECT a.id, a.category_name, cat.Count
FROM `categories` a
LEFT OUTER JOIN (
SELECT `categories`.`category_parent` , COUNT(*) AS Count
FROM `categories`
GROUP BY category_parent
)
cat ON a.id = cat.category_parent
WHERE a.category_parent = :category_parent
");
$stmt->bindParam(':category_parent', 1);
$stmt->execute();
$result = $stmt->fetchAll();
I have a query like that in one of my projects running on laravel 4.
Good Luck!
$query = mysql_query(" SET #c1=0; SELECT #c1 := #c1+1 as Week,
AVG(Temp) AS Average_Temperature FROM ( SELECT t1.*, COUNT(*) cnt
FROM test2 t1 LEFT JOIN test2 t2
ON t2.Date <= t1.Date
AND YEAR(FROM_UNIXTIME(t2.Date)) = YEAR(FROM_UNIXTIME(t1.Date))
AND MONTH(FROM_UNIXTIME(t2.Date)) = MONTH(FROM_UNIXTIME(t1.Date)) GROUP
BY Date ) t GROUP BY YEAR(FROM_UNIXTIME(Date)), MONTH(FROM_UNIXTIME(Date)), CEIL(cnt/7);" );
If I dont use SET #c1=0; I got no error... So whats the use of this on json php? Above code successfully queried on PHPMyAdmin.
edit: solved
Just enclose them in quotes .. See here $query = mysql_query(" your query ");
Like this..
$query = mysql_query("
SELECT AVG(Temp) AS Average_Temperature FROM (
SELECT t1.*, COUNT(*) cnt FROM test2 t1
LEFT JOIN test2 t2
ON t2.Date <= t1.Date
AND YEAR(FROM_UNIXTIME(t2.Date)) = YEAR(FROM_UNIXTIME(t1.Date))
AND MONTH(FROM_UNIXTIME(t2.Date)) = MONTH(FROM_UNIXTIME(t1.Date))
GROUP
BY Date
) t
GROUP BY
YEAR(FROM_UNIXTIME(Date)), MONTH(FROM_UNIXTIME(Date)), CEIL(cnt/7);
");
Disclaimer : Stop using mysql_* functions as they are deprecated. Switch to MySQLi or PDO instead.
Clearly, the set and select are incompatible as a single query. There is an easy work-around. Set the variable in the query:
SELECT #c1 := #c1+1 as Week, AVG(Temp) AS Average_Temperature
FROM (SELECT t1.*, COUNT(*) as cnt
FROM test2 t1 LEFT JOIN
test2 t2
ON t2.Date <= t1.Date AND
YEAR(FROM_UNIXTIME(t2.Date)) = YEAR(FROM_UNIXTIME(t1.Date)) AND
MONTH(FROM_UNIXTIME(t2.Date)) = MONTH(FROM_UNIXTIME(t1.Date))
GROUP BY Date
) t cross join
(select #c1 := 0) const
GROUP BY YEAR(FROM_UNIXTIME(Date)), MONTH(FROM_UNIXTIME(Date)), CEIL(cnt/7);