joinLeft Zend Framework, the same field names in different tables - zend-framework

I've got a problem. I'm trying to left join two tables with Zend Framework using $select object. Unfortunatly my tables has common field 'name' and when I'm joining one with the other the results I get is that name field from table overwrites the name field from the other.
My code is something like that:
$select->joinLeft ( array ('users' => 'users' ), $this->_name . '.employee_id = users.user_id', array ('*' ) );
How I can join tables and avoid this issue?

Use table aliases as you would in any normal sql query!
With Zend_Db aliases are written like this:
$select = $db->select()
->from(array('p' => 'products'),
array('product_id', 'product_name'))
->join(array('l' => 'line_items'),
'p.product_id = l.product_id',
array() ); // empty list of columns
The non-zend query would look like this:
SELECT p.product_id, p.product_name
FROM products AS p
JOIN line_items AS l ON p.product_id = l.product_id;

I guess it's bit late but to get all fields from two tables you must alias all the fields
$select = $db->select()
->from(array('u' => 'users'),
array('u.id'=>'u.id','u.employee_id'=>'u.employee_id','u.name'=>'u.name'))
->joinLeft(array('e' => 'employees'),
'e.id = u.employee_id',
array('e.id'=>'e.id','e.name'=>'e.name') );
And your array would look like:
array(
0=>array(
'u.id'=>'1',
'u.employee_id'=>'1',
'u.name'=>'John Doe',
'e.id'=>'1',
'e.name'=>'Worker'
),
1=>array(
...
));

Related

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'));

Join two table in zend_Validate_Db_NoRecordExists

I need to join two tables in zend_validate_Db_NoRecordExists. I need to use exclude for each table. I am using postgresql as db.
The usual way of invoking zend_validate_Db_NoRecordExists is as follows:
$validator = new Zend_Validate_Db_NoRecordExists(
array (
'table' => 'table1',
'field' => 'flag',
'exclude' => 'delete=0',
)
);
I think you must me able to use
$validator->getSelect()->_joinUsing($type, $name, $cond);

Yii fail to retrieve max column value

I have two models, one is Auction, the other is Bid.
An Auction has many Bids. they are associated by foreign key auction_id in Bid
Now, I want to find the max value of the Bid's price for each Auction.
$dataProvider = new CActiveDataProvider('Auction', array('criteria' => array(
'with' => array(
'bids' => array(
'alias'=>'b',
'group' => 'auction_id',
'select' => 'max(b.price) as maxprice'
)
)
)
)
);
And I have defined a maxprice property in Auction's model class.
However, if I try to retrieve the maxprice property, it returns NULL.
To be more specific, I render the $dataprovider to a view page, it fails to get the maxprice property.
PS:
I executed the query in mysql, the query result turns out to be correct.
So, there must be something wrong with the Yii code
SQL code:
SELECT `t`.`id` , max(b.price) as maxprice
FROM `auction` `t`
LEFT OUTER JOIN `bid` `b` ON (`b`.`auction_id`=`t`.`id`) GROUP BY auction_id
Put the value you want before the relation, like so:
$dataProvider = new CActiveDataProvider('Auction', array('criteria' => array(
'select' => 't.*, max(b.price) as maxprice',
'with' => array(
'bids' => array(
'alias'=>'b',
'group' => 'auction_id',
'together'=>true,
)
You can replace the "t.*" with specific field names if you like.
OR you can simply use the select, join and group attributes on your Auction model and skip the relation altogether.

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_Db_Table fetchAll and column names

I'm testing Zen_DB and Zend_DB_Table and I'm facing a problem:
Let's say I've got two tables
table A(id, title)
table B(id, title)
If I write something like
$db = $this->getDbTable()->getAdapter();
$query = "SELECT A.*, B.* FROM A INNER JOIN B on A.id = B.id"
$stmt = $db->query($query);
$rows = $stmt->fetchAll();
each resulting row is like ['id' => value, 'title' => value]
Question: How can the fetched rows be like ['A.id' => value, 'A.title' => value', 'B.id' => value, 'B.title' => value'] ?
Important: I don't want to modify the database schema
Your question was answered by this question