Can you please help me out to write the Laravel Raw Query for below Mysql query.
SELECT
SUM(IF(d.business_email_template_10_open = "Yes", 1,0)) AS `business_email_template_10_open`,
SUM(IF(d.business_email_template_11_open = "Yes", 1,0)) AS `business_email_template_11_open`
FROM dummy_email_track d
join recommend_email_send_by_cron r on d.user_id = r.user_id
join user_form_submission u on r.user_id = u.id'
where d.business_id = $businessId
If you can't use stored procedure, ignore my answer.
I think you can't use Laravel QueryBuilder cause something reason(I have a similar situation). How about using SP(stored procedure)?
Mysql SP
CREATE DEFINER=`your_mysql_id`#`%` PROCEDURE `get_usage_business_email_template`()
__SP:BEGIN
BEGIN
SELECT
SUM(IF(d.business_email_template_10_open = "Yes", 1,0)) AS `business_email_template_10_open`,
SUM(IF(d.business_email_template_11_open = "Yes", 1,0)) AS `business_email_template_11_open`
FROM dummy_email_track d
join recommend_email_send_by_cron r on d.user_id = r.user_id
join user_form_submission u on r.user_id = u.id'
WHERE d.business_id = $businessId
END;
END
And, Laravel call this SP like below
$result = DB::select('CALL get_usage_business_email_template()');
I hope you will save your time becasue my answer...
This should give you a headstart!
https://laravel.com/docs/5.6/database#running-queries
$results = DB::select('select * from users where id = :id', ['id' => 1]);
Make sure you give right id to your where clause. So in you case it would something like this:
(where d.business_id = :businessId, ['businessId' => 1])
Goodluck!
Please try this :
$data = DB::table('dummy_email_track as d')
->select('d.*','r.*','u.*')
->selectRaw('SUM(IF(d.business_email_template_10_open = "Yes", 1,0)) AS business_email_template_10_open')
->selectRaw('SUM(IF(d.business_email_template_11_open = "Yes", 1,0)) AS `business_email_template_11_open`')
->leftJoin('recommend_email_send_by_cron as r','d.user_id', '=', 'r.user_id')
->leftJoin('user_form_submission as u', 'r.user_id', '=', 'u.id')
->where('d.business_id','=', $businessId)
->get();
Related
I have a complicated query that I would like to translate either in Eloquent ORM or with the Query Builder for a Laravel site, but I can't do it, can someone help me?
Here is my SQL query
SELECT opp_id, risk_study.rst_id, risk_study.rst_status
FROM opportunity
LEFT JOIN risk_study ON risk_study.rst_id =
(SELECT risk_study_quote_vehicle.rst_id
FROM risk_study_quote_vehicle
INNER JOIN quote_vehicle ON quote_vehicle.quv_id = risk_study_quote_vehicle.quv_id
INNER JOIN quote ON quote.quo_id = quote_vehicle.quo_id
WHERE quote.opp_id = opportunity.opp_id
ORDER BY risk_study_quote_vehicle.rst_id DESC
LIMIT 0,1)
WHERE 1 = 1
AND opportunity.per_id_process = '5'
AND opportunity.opp_locked = '1'
Here is my solution.
But this query does not retrieve values from the risk_study table.
$opportunities = Opportunity::select('opp_id', 'risk_study.rst_id', 'risk_study.rst_status')
->leftJoin('risk_study', function ($join) {
$join->on('risk_study.rst_id', '=', DB::raw('"SELECT risk_study_quote_vehicle.rst_id FROM risk_study_quote_vehicle INNER JOIN quote_vehicle ON quote_vehicle.quv_id = risk_study_quote_vehicle.quv_id INNER JOIN quote ON quote.quo_id = quote_vehicle.quo_id WHERE quote.opp_id = opportunity.opp_id ORDER BY risk_study_quote_vehicle.rst_id DESC LIMIT 0,1"'));
})
->where([
['per_id_process', 5],
['opp_locked', 1],
])
->get();
Finally, I wrote the query and it works ! Thanks !
$opportunities = Opportunity::query()
->select(
'opp_id',
'risk_study.rst_id',
'risk_study.rst_status'
)
->from('opportunity')
->leftJoin('risk_study', function ($join) {
$join->where('risk_study.rst_id', function ($sub) {
$sub->select('risk_study_quote_vehicle.rst_id')
->from('risk_study_quote_vehicle')
->join('quote_vehicle', 'quote_vehicle.quv_id', 'risk_study_quote_vehicle.quv_id')
->join('quote', 'quote.quo_id', 'quote_vehicle.quo_id')
->whereColumn('quote.opp_id', 'opportunity.opp_id')
->orderByDesc('risk_study_quote_vehicle.rst_id')
->limit(1);
});
})
->where('opportunity.per_id_process', '5')
->where('opportunity.opp_locked', '1')
->get();
You should be able to use a Closure as the second parameter of where() inside your join Closure.
I don't think Laravel's query builder supports the LIMIT 0,1 statement.
I don't know why you need WHERE 1 = 1, but you should be able to use whereRaw for that.
When you're done, the result looks very alike a formatted SQL query.
$opportunities = Opportunity::query()
->select(
'opp_id',
'risk_study.rst_id',
'risk_study.rst_status'
)
->from('opportunity')
->leftJoin('risk_study', function ($join) {
$join->where('risk_study_quote_vehicle.rst_id', function ($sub) {
$sub->select('risk_study_quote_vehicle.rst_id')
->from('risk_study_quote_vehicle')
->join('quote_vehicle', 'quote_vehicle.quv.id', 'risk_study_quote_vehicle.quv_id')
->join('quote', 'quote.quo_id', 'quote_vehicle.quo_id')
->where('quote_opp_id', 'opportunity.opp_id')
->orderByDesc('risk_study_quote_vehicle.rst_id')
->limit(1);
});
})
->whereRaw('1 = 1')
->where('opportunity.per_id_process', '5')
->where('opportunity.opp_locked', '1')
->get();
Hi I want to know how can i do this query in Laravel 8 , I tried adding the join clause but not work as expected, i need join clause? Or maybe there is another form to do it. I search others examples but i donĀ“t see anythat help me. The query is the next:
DB::table('escandallo_p as esc')
->select("esc.material", "esc.referencia", "esc.ancho", "esc.proveedor", "esc.punto",
"esc.precio", "esc.consumo", "esc.veces", "esc.001", "esc.002", "esc.003", "esc.004",
"esc.005", "esc.006", "esc.007", "esc.008", "esc.009", "esc.010", "esc.011", "esc.um", "esc.merma", "esc.importe", "esc.tipo", "esc.xtalla", "esc.fase",
DB::raw("(select anulado from prototipos_p as p where p.prototipo = '".$scandal[0]->prototipo."' and p.tipo = 'c' and p.referencia = esc.referencia )"),
// ignore
//original query "(select anulado from prototipos_p as p where p.prototipo = ",$request->prototipo," and p.tipo = 'c' and p.referencia = esc.referencia ) as 'anulado'",
// "(select clase from prototipos_p as p where p.prototipo = ",$request->prototipo," and p.tipo = 'c' and p.referencia = esc.referencia ) as 'clase'")
//Converted query ->select('pro.anulado')->where('pro.prototipo', $request->prototipo)
// ->where("p.prototipo", "=", $request->prototipo)
->where("esc.id_escandallo", "=", $request->id_escandallo)
->where("esc.id_version", "=", $request->version)
->orderBy("id","asc")
->get();
!!!! I need to pass the esc.referencia to the sub select query
The second select is the conversion of the select inside "" ( i know this is wrong is only for explain it).
Thank you in advance for any suggestion.
Best regards
EDIT: I can solve my problem with DB::raw, but if anyone know others methos are welcome!
You need to pass callback to the join query to add the extra query to the laravel's join method,
Example from Laravel Doc:
DB::table('users')
->join('contacts', function ($join) {
$join->on('users.id', '=', 'contacts.user_id')
->where('contacts.user_id', '>', 5);
})
->get();
It is explained in Laravel's doc, Advanced Join Clauses
There is Subquery support too Subquery Joins,
Eg:
$latestPosts = DB::table('posts')
->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
->where('is_published', true)
->groupBy('user_id');
$users = DB::table('users')
->joinSub($latestPosts, 'latest_posts', function ($join) {
$join->on('users.id', '=', 'latest_posts.user_id');
})
->get();
These two might help you to achieve what you are trying
After test joins, joinSub, whereIn and other forms of doing this, I solved my problem using the DB::raw():
DB::table('escandallo_p as esc')
->select('parameters',....,
DB::raw("(SELECT column //(ONLY ONE)
FROM table
WHERE column = '".$parameter."' ...) AS nombre"),
)
->where('column', "=", $parameter)
->orderBy("id","asc")
->get();
SELECT e.match_id, e.team_id
FROM matches
LEFT JOIN match_events e
ON e.match_id = matches.id AND e.match_event_type_id = 1
Try this,
$result = DB::table('matches as M')
->leftjoin('match_events as E','E.match_id','=','M.id')
->where('E.match_event_type_id',1)
->select(['E.match_id','E.team_id'])
->get();
I have this code
$where = array('MONTH(c.cashDate)' => 'MONTH(NOW())');
$data['dataCash'] = $this->cash->cashList($where);
but it doesn't work, its create query like this
SELECT `c`.`cashId`, `c`.`cashDescription`, `c`.`cashDate`, `c`.`cashCategory`, `a`.`category`, `c`.`cashValue`, `t`.`typeid`, `t`.`type` FROM (`cash` c) LEFT JOIN `cashCategory` a ON `c`.`cashCategory` = `a`.`categoryId` LEFT JOIN `type` t ON `a`.`type` = `t`.`typeid` WHERE MONTH(c.cashDatee) = 'MONTH(NOW())' ORDER BY `c`.`cashDate` desc
when I try with phpmyadmin, it doesnt have a row
but when I remove ' from MONTH(NOW()) like this
SELECT `c`.`cashId`, `c`.`cashDescription`, `c`.`cashDate`, `c`.`cashCategory`, `a`.`category`, `c`.`cashValue`, `t`.`typeid`, `t`.`type` FROM (`cash` c) LEFT JOIN `cashCategory` a ON `c`.`cashCategory` = `a`.`categoryId` LEFT JOIN `type` t ON `a`.`type` = `t`.`typeid` WHERE MONTH(c.cashDatee) = MONTH(NOW()) ORDER BY `c`.`cashDate` desc
it works, how I call func in controller?
when you do this, it wont work
$where = array('MONTH(c.cashDate)' => MONTH(NOW()));
Just update your $where condition
$where = array('MONTH(c.cashDate)' => 'MONTH(NOW())');
into
$where = 'MONTH(c.cashDate) = MONTH(NOW())';
I am using symfony+doctrine, and I want to perform a delete query with a join. See below for my code I am currently using that works fine.
$sql = 'DELETE a
FROM a
INNER JOIN b ON a.b_id = b.id
WHERE b.c_id = :c_id';
$pdo = Doctrine_Manager::getInstance()->getCurrentConnection()->getDbh();
$stmt = $pdo->prepare($sql);
$params = array('c_id' => $c_id);
$stmt->execute($params);
Anyone know how I can do this using:
Doctrine_Core::getTable('a')
Or
Doctrine_Query::create()->delete()->from('a')
I have had no luck with either.
I just don't really want to use raw SQL in my app.
Something like this should do it
Doctrine_Query::create()
->delete('a a')
->innerJoin('a.b b')
->where('b.c_id = ?', $c_id)
->execute()