convert sql query to zend query - php

SELECT uls.prod_id,um.prod_image,um.prodname,SUM(msm.points)
FROM tbl_prod_selection AS uls
INNER JOIN tbl_prod_master AS um ON um.prod_id = uls.prod_id
INNER JOIN tbl_admin_prod_selection AS als ON als.user_id = uls.user_id
INNER JOIN tbl_prod_statistics_master AS msm ON (msm.user_id = uls.user_id AND msm.barcode_id = als.barcode_id)
WHERE uls.location_id = "18" AND uls.prod_code = "FLB"
GROUP BY uls.user_id;
can any one help to write zend query for this.
Thanks in Advance.

If you're using Zend_Db_Table, then you can assemble Zend_Db_Table_Select like below:
$select = $model->select()
->setIntegrityCheck(false)
->from(array('uls' => 'tbl_prod_selection'), array(
'uls.prod_id',
'um.prod_image',
'um.prodname',
'sum' => new Zend_Db_Expr('SUM(msm.points)'),
))
->join(array('um' => 'tbl_prod_master'), 'um.prod_id = uls.prod_id', array())
->join(array('als' => 'tbl_admin_prod_selection'), 'als.user_id = uls.user_id', array())
->join(array('msm' => 'tbl_prod_statistics_master'), 'msm.user_id = uls.user_id AND msm.barcode_id = als.barcode_id', array())
->where('uls.location_id = ?', '18')
->where('uls.prod_code = ?', 'FLB')
->group('uls.user_id');

Related

Zend Framework 2 join the same table multiple times using alias

I'm struggling to implement multiple left JOINs into ZF2. I've got first one working, but when I add another one, it doesn't work.
This is the working SQL query which I should implement into zf2:
SELECT
ac.ctr_id AS ctr_id,
ac.ctr_no AS ctr_no,
ac.ctr_marketer AS marketer,
ac.ctr_manager AS manager,
ac.ctr_recruiter AS recruiter,
l1.emp_realname AS marketer,
l2.emp_realname AS co_recruiter_manager,
l3.emp_realname AS recruiter
FROM
allcontracts AS ac
JOIN
lstemployees AS le ON ac.ctr_recruiter = le.emp_id
LEFT JOIN
lstemployees AS l2 ON ac.ctr_manager = l2.emp_id
LEFT JOIN
lstemployees AS l3 ON ac.ctr_recruiter = l3.emp_id
LEFT JOIN
lstemployees AS l1 ON ac.ctr_marketer = l1.emp_id
from my model:
.....
$where = new Where();
$this->table='allcontracts';
$select = new Select($this->table);
$select->columns(array('*')); // TODO add columns from allcontracts table
// This one works
$select->join('lstemployees', 'allcontracts.ctr_recruiter = lstemployees.emp_id');
// When I add this one below it doesn't work
$select->join(array('l2' => 'lstemployees'), 'allcontracts.ctr_manager = l2.emp_id', array('*'), 'left');
$where->like('ctr_no', '%LT');
if($id!='' && $id > 0)
$where->equalTo('ctr_id', $id);
$select->where($where);
$resultSet = $this->selectWith($select);
......
Any idea?
Here is what I propose:
<?php
use Zend\Db\Sql\Select;
$select = new Select();
$select->columns([Select::SQL_STAR])
->from(['ac' => 'allcontracts '])
->join(['le' => 'lstemployees'], 'ac.ctr_recruiter = le.emp_id', [])
->join(['l1' => 'lstemployees'], 'ac.ctr_marketer = l1.emp_id', ['marketer' => 'emp_realname'], Select::JOIN_LEFT)
->join(['l2' => 'lstemployees'], 'ac.ctr_manager = l2.emp_id', ['co_recruiter_manager' => 'emp_realname'], Select::JOIN_LEFT)
->join(['l3' => 'lstemployees'], 'ac.ctr_recruiter = l3.emp_id', ['recruiter' => 'emp_realname'], Select::JOIN_LEFT);
// to debug your query
die($select->getSqlString($dbAdapter->getPlatform()));
// if you haven't $dbAdapter, replace by null but the result will be quoted.

How to use COUNT and DISTINCT together in zend framework?

I'm trying to rewrite the below query in zend
SELECT COUNT(DISTINCT CPS.supplier_id, CPS.manufacturerid,CPS.categories_id)
FROM suppliers_report AS CPS
INNER JOIN category_brand B ON B.categories_id = CPS.categories_id AND B.manufacturerid = CPS.manufacturerid
INNER JOIN manufacturer m ON m.manufacturerid = CPS.manufacturerid
WHERE s.isactive=1 AND CPS.flg = 2 AND CPS.categories_id = c.parent_id
I tried the above query in zend as
$this->select()
->setIntegrityCheck(false)
->from(array('CPS' => 'suppliers_report'), array('CPS.supplier_id', 'CPS.manufacturerid', 'CPS.categories_id'))
->join(array('B' => 'category_brand'), 'B.categories_id=CPS.categories_id' AND 'B.manufacturerid = CPS.manufacturerid')
->join(array('m' => 'manufacturer'), 'm.manufacturerid = CPS.manufacturerid')
->where('s.isactive=1 AND CPS.flg = 2 AND CPS.categories_id = c.parent_id AND CPS.manufacturerid=ctb.manufacturerid');
I'm stuck on how to include count and DISTINCT in the above case.Please help
You'll need to use Zend_Db_Expr for functions like COUNT(), try something like the following:
$this->select()
->setIntegrityCheck(false)
->from(array('CPS' => 'suppliers_report'), array(new Zend_Db_Expr('COUNT(DISTINCT CPS.supplier_id, CPS.manufacturerid,CPS.categories_id)')))
->join(array('B' => 'category_brand'), 'B.categories_id=CPS.categories_id' AND 'B.manufacturerid = CPS.manufacturerid')
->join(array('m' => 'manufacturer'), 'm.manufacturerid = CPS.manufacturerid')
->where('s.isactive=1 AND CPS.flg = 2 AND CPS.categories_id = c.parent_id AND CPS.manufacturerid=ctb.manufacturerid');

Zend Framework 2: sql subquery

In ZF1 it worked like this:
$selectColumns = array(
'*',
'orders_total' => "(".$db->select()->from("orders", array("COUNT(*)"))->where("orders.parent_id=mytable.id").")",
);
$select = $db->select()->from('mytable', $selectColumns);
How to do this in the ZF2? Thanks.
Please try this.
$sql = new Sql($this->_adapter);
$mainSelect = $sql->select()->from('mytable');
$subQry = $sql->select()
->from('orders')
->columns(array('orderCount' => new \Zend\Db\Sql\Expression('COUNT(orders.id)')));
$mainSelect->columns(
array(
'id',
'orders_total' => new \Zend\Db\Sql\Expression('?', array($subQry)),
)
);
$statement = $sql->prepareStatementForSqlObject($mainSelect);
$comments = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($comments);
return $resultSet->toArray();
Link: ZF2 - subqueries
You can try this:
// Make your query here using the builder if you wish,
// but we will need to convert to string for the Expression
$sub = new Select('orders');
$sub->columns(array(new Expression('COUNT(*) as total')))
->where(array('id' => 4))
;
// You could just create an expression..
$subquery = new \Zend\Db\Sql\Expression("({$sub->getSqlString()})");
$select = new \Zend\Db\Sql\select('tablename'); // this is inside a
$select->columns(array('*', 'orders_total' => $subquery));
the output will be something like this:
SELECT
.*,
(SELECT COUNT(*) as total FROM "orders" WHERE "id" = '4') AS orders_total
FROM tablename
I haven't figured out a nice way of using the query builder to perform these kind of queries without having to use raw queries.
Without any more info you could try:
$selectColumns = array(
'*',
'orders_total' => "(".$db->select()->from("orders", array("COUNT(*)"))->where("orders.parent_id", "mytable.id").")",
);
$select = $db->select()->from('mytable', $selectColumns);
You will need to add at top with the use statements:
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Where;
You can try restructuring your SQL to something like:
SELECT
*,
SUM(IF(O.parent_id IS NULL, 0, 1)) AS orders_total
FROM mytable
LEFT JOIN orders O ON mytable.id = O.parent_id
Which you can represent using Zend Framework 2 as:
$select = new Select('mytable');
$select->columns(array(
'*',
'orders_total' => new Expression("SUM(IF(O.parent_id IS NULL, 0, 1))")
));
$select->join(array('O', 'orders'),
"mytable.id = O.parent_id",
Select::JOIN_LEFT);
$select->group(array('mytable.id'));
$result = $dbh->selectWith($select);
Assuming $dbh is your database adapter.

execute query in zend framework

I want to execute below query in zend framework. can anyone tell me how can I do that?
(SELECT `msg`.`message_sender_id`, `msg`.`message_receiver_id`, `msg`.`message_content`, `msg`.`message_sent_on`, `usr`.`user_name` AS `sender_name`
FROM `sc_message` AS `msg` INNER JOIN `sc_user` AS `usr` ON `msg`.`message_sender_id` = `usr`.`user_id`
WHERE `msg`.`message_id` = 3 ORDER BY `msg`.`message_sent_on`)
UNION
(SELECT `msg_slv`.`message_slave_sender_id`, `msg_slv`.`message_slave_receiver_id`, `msg_slv`.`message_slave_content`, `msg_slv`.`message_slave_sent_on`, `usr`.`user_name` AS `sender_name`
FROM `sc_message_slave` AS `msg_slv` INNER JOIN `sc_user` AS `usr` ON `msg_slv`.`message_slave_sender_id` = `usr`.`user_id`
WHERE `msg_slv`.`message_id` = 3 ORDER BY `msg_slv`.`message_slave_sent_on`)
I have written below code
$Query_1 = $this ->select()
->from(array('msg' => 'sc_message'), array('msg.message_sender_id', 'msg.message_receiver_id', 'msg.message_content', 'msg.message_sent_on'))
->joinInner(array('usr' => 'sc_user'), 'msg.message_sender_id = usr.user_id', array('usr.user_name as sender_name'))
->where('msg.message_id = ?',$message_id)
->setIntegrityCheck(false);
$this->_name = "sc_message_slave";
$this->_primary = "message_slave_id";
$Query_2 = $this ->select()
->from(array('msg_slv' => 'sc_message_slave'), array('msg_slv.message_slave_sender_id', 'msg_slv.message_slave_receiver_id','msg_slv.message_slave_content', 'msg_slv.message_slave_sent_on'))
->joinInner(array('usr' => 'sc_user'), 'msg_slv.message_slave_sender_id = usr.user_id', array('usr.user_name as sender_name'))
->where('msg_slv.message_id = ?',$message_id)
->setIntegrityCheck(false);
Assuming you're working from some Zend_Db_Table method
//your code...
$unionSelect = $this->getAdapter()->select()->union(array($Query_1, $Query_2));
//no you can execute it
$rows = $this->getAdapter()->fetchAll($unionSelect);

Lots and lots of joins in a Zend Query, hopefully just a slight tweak

Apologies for all this code, anyhow Im re-working a query into the Zend query way of working, this is what I have so far:
$db = Zend_Registry::get ( "db" );
$stmt = $db->query('
SELECT recipe_pictures.picture_id, recipe_pictures.picture_filename, course.course_name, cuisines.name, recipes.id, recipes.Title, recipes.Method, recipes.author, recipes.SmallDesc, recipes.user_id, recipes.cuisine, recipes.course, recipes.Created_at, recipes.vegetarian, recipes.Acknowledgements, recipes.Time, recipes.Amount, recipes.view_count, recipes.recent_ips, guardian_writers.G_item, guardian_writers.G_type
FROM recipes
LEFT JOIN course ON recipes.course = course.course_id
LEFT JOIN recipe_pictures ON recipes.id = recipe_pictures.recipe_id
LEFT JOIN cuisines ON recipes.cuisine = cuisines.id
LEFT JOIN guardian_writers ON recipes.author = guardian_writers.G_author
WHERE recipes.id = ?', $id);
$stmt->setFetchMode(Zend_Db::FETCH_ASSOC);
$recipes = $stmt->fetchAll();
return $recipes;
That one above works, trying to get the Zend version properly, my effort is below.
$db = Zend_Registry::get ( "db" );
$select = $db->select()
->from(array('r' => 'recipes'))
->join(array('c' => 'course'),
'r.course = c.course_id')
->join(array('rp' => 'recipe_pictures'),
'r.id = rp.recipe_id')
->join(array('cui' => 'cuisines'),
'r.cuisine = cui.id')
->join(array('gw' => 'guardian_writers'),
'r.author = gw.G_author')
->where(' id = ? ', $id);
$recipes = $db->fetchRow($select);
return $recipes;
If anyone can spot an error Id be very grateful, thanks
Use joinLeft instead of join to produce left joins.
To fetch specific columns from a table, rather than all (*) use this:
->from(array('r' => 'recipes'), array('id', 'title', 'method'))
or
->joinLeft(array('rp' => 'recipe_pictures'),
'r.id = rp.recipe_id',
array('picture_id', 'picture_filename')
)
To fetch no columns from a table, pass an empty array as the third parameter.
The join method provides an sql INNER JOIN. If you want to get a LEFT JOIN you should use joinLeft.

Categories