My current query is
select * from `users` where `group_id` = 1 and ((select count(*) from `works` inner join `user_work` on `works`.`id` = `user_work`.`work_id` where `user_work`.`user_id` = `users`.`id` and `work_duration_id` >= 3) >= 1)
For this query I have written following eloquent method in laravel 4.2 and it is working fine
$u = User::where('group_id', '=', 1);
$u = $u->where(function($m) use($minWorkDuration,$searchCriteria){
$m = $m->whereHas('work', function($q) use($minWorkDuration){
$q->where('work_duration_id', '>=', $minWorkDuration );
});
});
But I want to change in my query little bit and this is
select * from `users` where `group_id` = 1 and ((select count(*) from `works` inner join `user_work` on `works`.`id` = `user_work`.`work_id` where `user_work`.`user_id` = `users`.`id` and (SELECT SUM(`work_duration_id`) from `works` group by `user_id`) >= 3) >= 1)
If I want to write this query then what will be in eloquent method. If anybody is there please suggest me how to write this query in eloquent method in laravel 4.2.
Thanks in advance.
Related
select * from `eplan_vacancy` where `reference_id` in
(select `eplan_ep_details`.`reference_id`
from `eplan_ep_details`
inner join `eplan_court_cases` on `eplan_ep_details`.`reference_id` = `eplan_court_cases`.`reference_id`
where `ep_cc_status` = 1
group by `eplan_court_cases`.`reference_id`)
and `is_form_submitted` = 1
and `st_code` in ('U05', 'S13', 'S01')
group by `reference_id`
order by `created_at` desc
You can use closure as the second parameter of the whereIn method.
whereIn($column, $values, $boolean = 'and', $not = false)
$return = DB::table('eplan_vacancy')
->whereIn('reference_id', function ($query) {
return $query->select('eplan_ep_details.reference_id')
->from('eplan_ep_details')
->join('eplan_court_cases', 'eplan_ep_details.reference_id', '=', 'eplan_court_cases.reference_id')
->where('ep_cc_status', 1)
->groupBy('eplan_court_cases.reference_id');
})
->where('is_form_submitted', 1)
->whereIn('st_code', ['U05', 'S13', 'S01'])
->groupBy('reference_id')
->orderBy('created_at', 'desc');
dd($return->toSql());
Result
select * from `eplan_vacancy` where `reference_id` in
(
select `eplan_ep_details`.`reference_id`
from `eplan_ep_details`
inner join `eplan_court_cases` on `eplan_ep_details`.`reference_id` = `eplan_court_cases`.`reference_id`
where `ep_cc_status` = ?
group by `eplan_court_cases`.`reference_id`
)
and `is_form_submitted` = ?
and `st_code` in (?, ?, ?)
group by `reference_id`
order by `created_at` desc
Here is a full eloqent query that you can use to generate above query, Here i used Models that you need to change according to your model name.
EplanVacnacy: Model for table "eplan_vacancy"
$result = EplanVacnacy::whereIN('reference_id',function($q){
$q->from('eplan_ep_details')
->select('eplan_ep_details.reference_id')
->innerJoin('eplan_court_cases','eplan_ep_details.reference_id','=','eplan_court_cases.reference_id')
->where('eplan_ep_details.ep_cc_status',1)
->groupBy('eplan_court_cases.reference_id')
->get();
return $q;
})
->where('is_form_submitted',1)
->whereIN('st_code',['U05', 'S13', 'S01'])
->groupBy('reference_id')
->orderBy('created_at','desc')
->get();
Those are the queries that form the collection to be pushed to the laravel datatables builder:
foreach (Session::get('trienios') as $trienio) {
$oeTrienios = $oeTrienios->where('data_trienio', $trienio->trienio)->whereHas('curso', function ($query) use ($trienio) {
$query->where('curso', $trienio->curso);
});
}
$union = Trienio::with('curso')->whereHas('curso', function ($query) use ($coordinatedCourse) {
$query->where('curso', $coordinatedCourse);
})->union($oeTrienios);
$trienios = \DB::table(\DB::raw("({$union->toSql()}) as x"))->select(['data_trienio']);
There is a tutorial on the official laravel-datatables site that "explains" how to work with united queries, however it is pretty vague and can't realistically explain anything, and besides, when I tried to add a code they had on the tutorial:
$trienios = \DB::table(\DB::raw("({$union->toSql()}) as x"))
It gives me the following error:
SQLSTATE[HY000]: General error: 2031 (SQL: select count(*) as aggregate from (select `data_trienio` from ((select * from `trienios` where exists (select * from `cursos` where `trienios`.`curso_id` = `cursos`.`id` and `curso` = ?)) union (select * from `trienios` where `data_trienio` = ? and exists (select * from `cursos` where `trienios`.`curso_id` = `cursos`.`id` and `curso` = ?) and `data_trienio` = ? and exists (select * from `cursos` where `trienios`.`curso_id` = `cursos`.`id` and `curso` = ?))) as x) count_row_table)
If I, however, attach the parameter ->get() to the ->union($oeTrienios), it will work just fine, however, the collection will come unorderable on the datatable.
How do I solve this issue? Any help would be very welcome.
P.S - Link to the demo: https://datatables.yajrabox.com/fluent/union
The subquery $union->toSql() has only sql code without parameters and you need call bindings. See here and code will be:
$trienios = \DB::table(\DB::raw("({$union->toSql()}) as x"))
->select(['data_trienio'])
->mergeBindings($union);
how would I go about writing this SQL query in Laravel 4.2 using eloquent?
SELECT *
FROM participants
WHERE user_id IN (1, 2)
GROUP BY convo_id
HAVING count(DISTINCT user_id) = 2
AND count(DISTINCT convo_id) = 1
I tried this already
Participant::whereIn('user_id', $participantIds)
->groupBy('convo_id')
->havingRaw('count(DISTINCT user_id) = '. sizeof($participantIds))
->whereRaw('count(DISTINCT convo_id) = 1')
->get();
But I get this error
SQLSTATE[HY000]: General error: 1111 Invalid use of group function (SQL: select * from `participants` where `user_id` in (1, 2, 4) and count(DISTINCT convo_id) = 1 group by `convo_id` having count(DISTINCT user_id) = 3)
My mistake. whereRaw should also be havingRaw.
Participant::whereIn('user_id', $participantIds)
->groupBy('convo_id')
->havingRaw('count(DISTINCT user_id) = '. sizeof($participantIds))
->havingRaw('count(DISTINCT convo_id) = 1')
->get();
Try groupBy at last
Participant::whereIn('user_id', $participantIds)
->havingRaw('count(DISTINCT user_id) = '. sizeof($participantIds))
->whereRaw('count(DISTINCT convo_id) = 1')
->groupBy('convo_id')
->get();
I want to write this query in laravel 5.2
SELECT b.id,
TotalP,
b.booking_amount
FROM booking b
LEFT JOIN
(SELECT sum(amount) AS TotalP,
booking_id
FROM payment
GROUP BY booking_id) AS T ON b.id = T.booking_id
WHERE COALESCE(TotalP, 0) < b.booking_amount
My Question is related to this post.
I wrote a query after searching and studying but It is not working and need more constraint
$result = DB::table('my_booking')
->select('booking_name')
->leftJoin(DB::raw('(SELECT booking_id,sum(amount) as TotalP FROM `my_payment` GROUP BY booking_id) TotalPayment'), function($join)
{
$join->on('my_booking.id', '=', 'TotalPayment.booking_id');
})
->get();
Sql query to get data diffrence of total in 2 tables
You can try this,
$booking_payments = Booking::with('Payment')->find(1);
$total = 0;
foreach($booking_payments->payment as $booking_payment){
$total += $booking_payment->amount;
}
if($booking_payments->booking_amount == $total){
// if the total and booking_amount is equal
}
This should work in Laravel and give you the same exact result as your MySQL query. I moved COALESCE into the subquery select area so that you don't have to write a raw DB where statement in Laravel.
$sql_subquery = "(SELECT COALESCE(SUM(amount),0) AS TotalP,
booking_id
FROM payment
GROUP BY booking_id) AS T";
$result = DB::table('booking AS b')
->leftJoin(DB::raw($sql_subquery), 'b.id', '=', 'T.booking_id')
->where('T.TotalP','<', 'b.booking_amount')
->select('b.id','T.TotalP','b.booking_amount')
->get();
Im working on a Symfony project and I want to create Doctrine Query for this SQL.
USER table :
columns -
NICK_NAME
REVIEWS table:
columns -
USER_ID
, REVIEW,
CREATED_AT
Thank you
SELECT
`USER`.NICK_NAME,
REVIEWS.REVIEW,
REVIEWS.CREATED_AT
FROM
REVIEWS
INNER JOIN `USER` ON REVIEWS.USER_ID = `USER`.ID
WHERE
REVIEWS.MOVIE_ID = 625
GROUP BY
REVIEWS.USER_ID
I tried something like this
$q = Doctrine_Query::create()
->select("u.NICK_NAME,r.REVIEW,r.CREATED_AT")
->from('REVIEWS r')
->innerJoin('`USER` ON REVIEWS.USER_ID = `USER`.ID')
->where('REVIEWS.MOVIE_ID = 625')
->groupBy('REVIEWS.USER_ID');
and got this:
500 | Internal Server Error | Doctrine_Exception Couldn't find class `USER`
Without using complex DQL in Symfony you can use simple SQL.
Try this function in the controller where you want to run the DQL.
function getUserReviews($params) {
$query = "SELECT REVIEWS.REVIEW, `USER`.NICK_NAME, REVIEWS.CREATED_AT FROM REVIEWS INNER JOIN `USER` ON REVIEWS.USER_ID = `USER`.ID WHERE REVIEWS.MOVIE_ID ='".$params."'";
return Doctrine_Manager::getInstance()->getCurrentConnection()->fetchAssoc($query);
}
You Should Specify Entity name not table name in DQL like this YourBundleName:EntityName
Use it like this:
$q = Doctrine_Query::create()
->select("u.NICK_NAME,r.REVIEW,r.CREATED_AT")
->from('REVIEWS r')
->innerJoin('YourBundleName:EntityName ON REVIEWS.USER_ID = `USER`.ID')
->where('REVIEWS.MOVIE_ID = 625')
->groupBy('REVIEWS.USER_ID');
Alternative Solution if above solution doesn’t work:
$q = Doctrine_Query::create()
->select("u.NICK_NAME,r.REVIEW,r.CREATED_AT")
->from('REVIEWS r')
->innerJoin('YourBundleName:EntityName', 'USER_ID')
->where('REVIEWS.MOVIE_ID = 625')
->groupBy('REVIEWS.USER_ID');
If that doesn't work, use Inner join in following manner:
->InnerJoin('YourBundleName:Entity', '<alias>', Expr\Join::ON, $qb->expr()->eq('IDENTITY(<alias.<clummn_name>)', '<comapring_column>'))
inner Join from Doctrine2 Documentation:
Example -
$qb->innerJoin('u.Group', 'g', Expr\Join::WITH, qb->expr()->eq('u.status_id', '?1'))
$qb->innerJoin('u.Group', 'g', 'WITH', 'u.status = ?1')
$qb->innerJoin('u.Group', 'g', 'WITH', 'u.status = ?1', 'g.id')
innerJoin Method Prototype:
innerJoin($join, $alias, $conditionType = null, $condition = null, $indexBy = null);
Find More Here
Hope this will help you.