Zend Framework: Zend_Db_Select - how to join custom subquery table? - zend-framework

$select->joinRight(array('i' => '(SELECT * FROM images ORDER BY image_id)'),'i.ad_id = '. $main .'.id',$imarray);
Like that doesn't work. Subquery getting inside quotes.
Like that:
RIGHT JOIN `(SELECT * FROM images ORDER BY image_id)` AS `i` ON i.ad_id = a.id
Thanks ;)

Use
$select->joinRight(
array('i' => new Zend_Db_Expr('(SELECT * FROM images ORDER BY image_id)')),
'i.ad_id = '. $main .'.id',
$imarray
);

I feel This is easier to read and navigate...
$sub = $this->select()
->setIntegrityCheck(false)
->from(array('i' => 'images'), array('*'))
->order('i.image_id');
$select = $this->select()
->setIntegrityCheck(false)
->from(array('m' => 'MAIN_TABLE'), array('*'))
->joinRight(array('i' => $sub), 'i.ad_id = m.id', array('*'));
return $this->select($select);

Related

Zend\Db\Sql\Select multiple where (combination between AND and OR)

I'm a little stuck at a query with multiple where. I want to 'translate' the query bellow in my Zend\Db\Sql\Select query:
SELECT `users`.*, `users_metas`.*
FROM `users` INNER JOIN `users_metas` ON `users`.`ID` = `users_metas`.`parent_id`
WHERE `role` = 'admin'
AND (
`users`.`username` like '%q_word%'
OR
(`users_metas`.`meta_key` = 'name'
AND
`users_metas`.`meta_value` like '%q_word%')
)
ORDER BY `date_added` ASC
I tried something like this:
$select = new Select();
$select->where(array('role' => 'admin'));
$select->join('users_metas', 'users.ID = users_metas.parent_id');
but I'm stuck to this where:
AND (
`users`.`username` like '%q_word%'
OR
(`users_metas`.`meta_key` = 'name'
AND
`users_metas`.`meta_value` like '%q_word%')
)
Thank you!
$where = new Where();
$where
->equalTo('role', 'admin')
->nest()
->like('users.username', '%q_word%')
->or
->like('users_metas.meta_key', 'name')
->or
->like('users_metas.meta_value', '%q_word%')
->unnest();
$select = new Select();
$select
->from('users')
->join('users_metas', 'users.ID = users_metas.parent_id')
->where($where)
->order('date_added');

Column already exists in LeftJoin with Zend

With relationship and joins I'm trying get the latest post of each customer.
But I don't really get it to work. I get error:
Column already exists: 1060 Duplicate column name 'custID'
Based on my searching both here and Google it could have been for * but I have removed so all table columns is specified by name so I don't get why I get column already exists?
$db = $this->getDbTable();
// create sub query
$subSql = $db->select()
->setIntegrityCheck(false)
->from(array('s1' => 'sales'), array('s1.custID', 's1.saledate'))
->joinLeft(array('s2' => 'sales'), 's1.custID = s2.custID AND s1.saledate < s2.saledate', array('s2.custID', 's2.saledate'))
->where('s2.custID IS NULL')
->limit(1);
//main query
$sql = $db->select()
->setIntegrityCheck(false)
->from(array('customers' => 'customers'), array("customers.custID"))
->joinLeft(array('sale_tmp' => new Zend_Db_Expr('(' . $subSql . ')')), "customers.custID = sale_tmp.custID", array('sale_tmp.custID'));
//echo $sql->assemble();
//exit;
$resultSet = $db->fetchAll($sql);
return $resultSet;
Since two of your tables have the field custID, there is a conflict about how to populate the custID value in your joined table.
You need to provide a column-alias for one of them. The signature of the joinLeft() method is:
joinLeft($table, $condition, [$columns])
The third argument $columns can be a straight integer-indexed array of columns (as you are using) or it can be an associative array whose values are the columns, but whose keys are the column-aliases.
So perhaps try something like:
// create sub query
// add alias for the custID field
$subSql = $db->select()
->setIntegrityCheck(false)
->from(array('s1' => 'sales'), array('s1.custID', 's1.saledate'))
->joinLeft(array('s2' => 'sales'), 's1.custID = s2.custID AND s1.saledate < s2.saledate', array('sales_custID' => 's2.custID', 's2.saledate'))
->where('s2.custID IS NULL')
->limit(1);
// main query
// add alias for custID field
$sql = $db->select()
->setIntegrityCheck(false)
->from(array('customers' => 'customers'), array("customers.custID"))
->joinLeft(array('sale_tmp' => new Zend_Db_Expr('(' . $subSql . ')')), "customers.custID = sale_tmp.custID", array('temp_custID' => sale_tmp.custID'));

zend framework subquery

I am using zend framework 1.12. I have following query to run.
"SELECT name,(select count(*) from org_quote_template_items where org_quote_template_items.quote_template_id = org_quote_templates.`id` ) as total_line_item FROM `org_quote_templates`"
In my model file , I created it like this. following is my model file.
class default_Model_DbTable_QuoteTemplates extends Zend_Db_Table_Abstract
{
/**
* Name of the original db table
*
* #var string
*/
protected $_name = 'org_quote_templates';
public function getAllTemplate($where){
$select = $this->select();
$subquery = " (SELECT COUNT(*) FROM org_quote_template_items WHERE org_quote_template_items.quote_template_id = org_quote_templates.`id` )";
$select->from(array($this), array('org_quote_templates.*','total_line_items' => new Zend_Db_Expr($subquery)));
$select = $select->where('organization_id = ?',$where['org_id']);
$adapter = new Zend_Paginator_Adapter_DbSelect($select);
$paginator = new Zend_Paginator($adapter);
$paginator->setItemCountPerPage(
Zend_Registry::get('config')->paginator->general);
pr($adapter);
exit;
}
}
I am getting following error when I run the code.
" exception 'Zend_Db_Table_Select_Exception' with message 'Select query cannot join with another table' "
please let me know what should I do ?
There is an error in your request. You should have:
$select = $this->select ();
$subquery = "(SELECT COUNT(*) FROM dtempls WHERE order_id = orders.id)";
$select->from ($this, array (
'id',
'total_line_items' => new Zend_Db_Expr ($subquery)
));
I think you have to use setIntegrityCheck(false) for accomplishing that. Check this link
You can try this way in zend
$this->select()
->setIntegrityCheck(false)
->from(array('oqt' => 'org_quote_templates'),array('total_line_item'))
->joinLeft(array('oqti' => 'org_quote_template_items'), 'oqti.quote_template_id = oqt.id', array(count(*) as count))

Zend Framework Query with Joins

I am trying to replicate this query using zend framework:
SELECT
activitytype.description,
activity.datecompleted
FROM
clientactivity
INNER JOIN activity
ON activity.activityID = clientactivity.activityid
INNER JOIN activitytype
ON activitytype.activitytypeid = activity.activitytypeid
WHERE
clientactivity.clientid = 100
This is what I have so far:
$select = $dbTable->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
$select->setIntegrityCheck(false);
$select->where('clientactivity.clientid = ?', $clientID);
$select->join('activity', 'activity.activityid = clientactivity.activityid');
$select->join('activitytype', 'activitytype.activitytypeid = activity.activitytypeid');
$select->columns(array('activitytype.description', 'activity.datecompleted'));
I seem to be having problems with the columns option, it doens't seem to be limiting the columns and I am ending up with
clientactivity.* etc in the column list in the query.
What am I doing wrong?
Thanks,
Martin
Try instead of the $select->columns();
$select->from('activitytype.description', 'activity.datecompleted');
Reference - http://framework.zend.com/manual/en/zend.db.select.html
UPDATE:
This example makes us of a generic database handler:
$db = Zend_Db::factory('Pdo_Mysql', array(
'host' => '127.0.0.1',
'username' => 'yourusername',
'password' => 'somepassword',
'dbname' => 'yourdbname'
));
$select = $db->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
$select->from('tableName','fieldName')
->join('joinTable', 'joinTable.keyId = tableName.keyId',array())
->where('tableName.userId = ?', $userId);
$resultSet = $db->fetchAll($select);
The key piece is the blank array at the end of the join statements that specifies no records to be returned from the joined table.

Zend Join Models

I have models of my tables and would like to do a join using a model as opposed to to a table.
For example, instead of:
$select = $this->select()
->from(array('p' => 'products'),
array('product_id', 'product_name'))
->join(array('l' => 'line_items'),
'p.product_id = l.product_id',
->limit(20, 10);
where I specify the table names and columns I want to join, can I not use my models?
$select = $this->select()
->from(array('p' => 'products'),
array('product_id', 'product_name'))
->join(array('l' => Model_Table1::tableName()),
'p.product_id = l.product_id',
->limit(20, 10);
no ... u cann't join two model ... these are class which can be include .. so u can only use these class in controller or can include in another model too ... according to application or requirement
I don't see why not, if your model has a static variable with the name and a static function to return the variable:
protected static $table = 'dbname';
public static function tableName() {
return self::$table;
}
Is it worth it though? Is the table name ever going to change?
You must set integrity check is false. Like this
$select = $this->select()
->setIntegrityCheck(false)
->from(array('p' => 'products'),
array('product_id', 'product_name'))
->join(array('l' => 'line_items'),
'p.product_id = l.product_id',
->limit(20, 10);