I have the following query
(select informed from evaluations where releases_id="1234") AS INFO
ZEND frameword query:
$get_details = $db->select()
->from(array('INFO'=>'evaluations'), 'informed')
->where('releases_id =?',"$row[id]");
The above gives
SELECT `INFO`.`informed` FROM `evaluations` AS `INFO` WHERE (releases_id ='1214')
but I would like to get
(select informed from evaluations where releases_id="1234") AS INFO
Can anyone please guide me to build the right query?
Starting from your request :
$get_details = $db->select()
->from(array('INFO'=>'evaluations'), 'informed')
->where('releases_id =?',"$row[id]");
Try this to rename your subquery, it should work :
$get_details = $db->select()->from(array('INFO' => $get_details))
I'm not an expert in Zend but you may try something along the lines of
$subquery = $this->select()
->from('evaluations'), array('informed'))
->where('releases_id = ?', $row[id]);
$main = $this->select()
->from('info' => new Zend_Db_Expr('(' . $subquery . ')'));
$result = $this->fetchAll($main);
Related
Given a query :
SELECT t1.c1, t2.c1 FROM t1,t2;
How to write it in Zend framework without using joins ?
Try the below join query in zend framework,
$sql = $this->tableGateway->getSql()->select();
$sql->join('table2', "table1.column1 = table2.column1", array(column1,column2), 'inner');
Assuming you have a common field (we'll call it c2), you can do something approximating a JOIN without actually doing a JOIN.
// we'll assume $adapter is an instance of Zend_Db_Adapter_Mysqli
$cols = $adapter->fetchAll(
'
SELECT
t1.c1 AS t1c1,
t2.c1 AS t2c1
FROM t1, t2
WHERE t1.c2 = t2.c2
'
);
Using Zend_Db_Select you can do it this way
$rows = $adapter->select()
->from('t1', array('t1c1' => 'c1'))
->from('t2', array('t2c1' => 'c1'))
->where('t1.c2 = t2.c2')
->query()->fetchAll();
I have a SQL statement
select a.username
from friendships f1
inner join friendships f2 on (f1.user = f2.friend and f1.friend = f2.user)
inner join users a ON (a.user_id = f1.friend) where f1.user = '24'
I excuted this query on phpmyadmin and it's OK.
But I don't knoe how to do this query in Zend
$select = $this->_db_table->select()
->setIntegrityCheck(false)
->from(array('f1' => 'friendships'), array('u.*'))
->joinInner(array('f2' => 'friendships'),
array('f1.user = f2.friend', 'f1.friend = f2.user'))
->joinInner(array('u' => 'users'), array('u.user_id = f1.friend'))
->where('f1.user = ?', $user_id);
I use this code but it doesn't work, any ideas?
What version of ZF are you using ? Here is how you would do it in ZF 1.12:
$this->_db_table->getAdapter()->select()
->from("friendships as f1")
->joinInner("friendships as f2", "f1.user = f2.friend AND f1.friend = f2.user")
->joinInner("users as a", "a.user_id = f1.friend", array("a.username"))
->where("f1.user = ?", $user_id)
->query()
->fetchAll(); // use ->fetch() if you only want to retrieve one record
Read more on in the manual:
What exactly doesn't work? Are you getting a PHP/Zend error or a SQL error?
You can use $select->assemble() to examine the prepared query and compare it against your expectation:
echo $select->assemble();
Using Zend DB. I am trying to figure out how to write this query using the DB Class.
select
org.orgid
org.role
user.userid
user.firstname
from orgTable org
join userTable user on org.userid = user.userid
where org.orgid = 'generated-id'
from the documents I understand or think I understand how to do it with one definition using an AS like condition, but even then Im still not sure. Eventually this will branch out into a multi table join, based on cross table conditions so not sure how to achieve this to begin with.
I think this is what are you looking for
$db = Zend_Db::factory( ...options... );
$select = $db->select()
->from(array('org' => 'orgTable'),
array(
'orgid' => 'org.orgid',
'role' =>'org.role',
'userid' =>'user.userid',
'firstname' =>'user.firstname'
))
->join(array('user' => 'userTable'),
'org.userid = user.userid',array())
->where('org.orgid = ?',$generated_id);
Here is a Zend_Db_Select that returns the result you are looking for.
$select = $db->select()
->from(array('org' => 'orgTable'), array('orgid', 'role'))
->join(array('user' => 'userTable'), 'org.userid = user.userid', array('userid', 'firstname'))
->where('org.orgid = ?', 'generated-id');
You can use the array notation for table names to get the aliased names in the query.
Hope that helps.
In zend framework 2 , the following code helps you what are you looking for
$generated_id = 1 ;
$select = new \Zend\Db\Sql\Select( array('org' =>'orgTable'));
$select->columns(array('orgid','role') )
->join( array('user' => 'userTable'),
'org.userid = user.userid',
array('userid','firstname')
)->where( array('org.orgid' => $generated_id ) );
if your adapter platform is mysql, then for printing sql
$mysqlPlatform = new \Zend\Db\Adapter\Platform\Mysql();
echo $select->getSqlString( $mysqlPlatform );
which print sql as
SELECT
`org`.`orgid` AS `orgid`,
`org`.`role` AS `role`,
`user`.`userid` AS `userid`,
`user`.`firstname` AS `firstname`
FROM
`orgTable` AS `org`
INNER JOIN `userTable` AS `user`
ON `org`.`userid` = `user`.`userid`
WHERE
`org`.`orgid` = '1'
I have this query:
SELECT
groups.name
categories.name,
categories.label
FROM
groups
JOIN
categories
ON
(categories.group1 = groups.id
OR
categories.group2 = groups.id)
AND
groups.label = :section
AND
categories.active = 1
Now, this is my JOIN using Zend_Db_Select but it gives me array error
$select->from($dao, array('groups.name', 'categories.name', 'categories.label'))
->join(array('categories', 'categories.group1 = groups.id OR categories.group2 = groups.id'))
->where('groups.label = ?', $group)
->where('categories.active = 1');
My error:
Exception information:
Message: Select query cannot join with
another table
Does anyone know what I did wrong?
UPDATE / SOLUTION:
I've found the solution thanx to Eran. I just post the solution here in case anyone else is stuck on a problem like this one. The solution is:
$db = Zend_Registry::get('db');
$dao = new Default_Model_Db_CategoryDao('db');
$select = $dao->select();
$select->setIntegrityCheck(false)
->from(array('c' => 'categories'), array('name', 'label'))
->join(array('g' => 'groups'), 'c.group1 = g.id OR c.group2 = g.id', 'g.label')
->where('g.label = ?', $group)
->where('c.active = 1');
return $dao->fetchAll($select);
You are using a Zend_Db_Table_Select object. Those by default have integrity check enabled and cannot select data that is outside of their table.
You can turn it off by adding -> setIntegrityCheck(false) to the select object before querying with it.
You can read more about it in the manual under Select API -> Advanced usage
I'm pretty sure this is not possible in Zend Framework (I have searched the Web, the documentation and issue tracker) but I just want to make sure so I'm asking here.
$select = $this->select();
$select->union($select1, $select2);
That doesn't work of course. To explain what I need. I need to use UNION() to merge 2 tables in a SELECT query, I know I could just do:
$select = "$select1 UNION $select2";
The problem is that would return a string and I need to get a select object so I can use it with Zend_Paginator.
I have already solved the issue by modifying my database architecture but I'm just curious if there is some workaround for this.
Here's what I've done to make a union:
$select = $this->select();
//common select from both sides of the union goes here
$select1 = clone($select);
//select1 specifics here
$select2 = clone($select);
//select 2 specifics here
$db = $this->getAdapter();
$pageselect = $db->select()->union(array("($select1)", "($select2)"));
Remember Db_Select's __toString will print out the SQL generated by that select, to help you debug.
Zend_Db_Select has a union method so I'd have thought it is possible, if you can build your query using a select object. I haven't used Zend_Db_Select (or the table subclass) with union but I'd imagine you can do something like
$select = $this->select()
->where('blah')
->union($sql);
a complete example:
public function getReservationById($id)
{
if(!$id) return null;
$sql = $this->table->select();
$sql->union(array(
$this->table->select()->where('id=?', $id),
$this->tableFinished->select()->where('id=?', $id),
$this->tableCanceled->select()->where('id=?', $id),
$this->tableTrashed->select()->where('id=?', $id)
));
echo $sql->__toString();
}
and the generated query:
SELECT reservations.* FROM reservations WHERE (id='5658') UNION SELECT res_finished.* FROM res_finished WHERE (id='5658') UNION SELECT res_cancel.* FROM res_cancel WHERE (id='5658') UNION SELECT res_trash.* FROM res_trash WHERE (id='5658')
This practical example shows a function that returns a rowset of either latest or if a available favourite blog entries of a specific year (artwork blog):
public function fetchBestOf($year)
{
$selectLatest = $this->select()->where('isHidden = 0')
->where('YEAR(dateCreated) = ' . $year)
->where('isHighlight = 0');
$selectHighlights = $this->select()->where('isHidden = 0')
->where('YEAR(dateCreated) = ' . $year)
->where('isHighlight = 1');
$selectUnion = $this->select()->union(array($selectLatest, $selectHighlights), Zend_Db_Select::SQL_UNION_ALL)
->order('isHighlight DESC')
->order('dateCreated DESC')
->order('workID DESC')
->limit('5');
$rowset = $this->fetchAll($selectUnion);
return $rowset;
}
The best way Zend suggest is like follows....
$sql = $this->_db->select()
->union(array($select1, $select2,$select3))
->order('by_someorder');
echo $sql->__toString();
$stmt = $db->query($sql);
$result = $stmt->fetchAll();
echo will show the query
Here $select1, $select2, $select3 can be different select queries with same
number of columns...
This is how it works for me:
$select1 = $this->select();
$select2 = $this->select();
After getting the necessary data in both queries the UNION syntax goes like this:
$select = $this->select()->union(array('('.$select1.')', '('.$select2.')'));