I want to make inner join between two tables
Visit table has
Report table has
Each visit has many reports ,I want to select all reports with specified visit target
I make like this but it donesn't work
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select();
$rows = $select->from('visits_tb', array('target', 'visit_id'))
->joinInner('report_tb', 'visits_tb.visit_id= report_tb.visit_id', array('visit_id', 'rep_id'))
->where("visits_tb.visit_id=$id");
You can try the following; maybe its a bit clearer if you use table aliases:
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select()
->from(array('v' => 'visits_tb'), array('target', 'visit_id', 'rep_id'))
->joinInner(array('r' => 'report_tb'), 'v.visit_id = r.visit_id')
->where('v.visit_id = ?', $id);
$query = $select->query();
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select();
$select = $select->from('visits_tb', array('target', 'visit_id'))
->joinUsing('report_tb', 'visit_id', 'rep_id')
->where("visits_tb.visit_id=?",$id);
ZF uses inner join by default so joinInner == join . Since name of FK = PK hence you can use joinUsing .
$rows = $db->fetchAll($select);
I think better solution is to use Zend's relationship in this case
http://framework.zend.com/manual/en/zend.db.table.relationships.html
class Visit extends Zend_Db_Table_Abstract
{
protected $_name = 'visit';
protected $_primary = 'visit_id';
}
class Report extends Zend_Db_Table_Abstract
{
protected $_name = 'report';
protected $_primary = 'rep_id';
protected $_referenceMap = array(
'Visit' => array(
'columns' => 'visit_id',
'refTableClass' => 'Visit',
'refColumns' => 'visit_id'
))
}
With this config You should be able to fetch dependent rowset with reports
$visitTable = new Visit();
//fetch visit with id 13
$visitRow = $visitTable->find(13)->current();
$reportRowset = $visitRow->findDependentRowset('Report');
What's beneficial You can instantly go on and process results
//for example
foreach ($reportRowset as $report) {
$report->someField = 'newValue';
$report->save();
}
What happens if you turn it the other way around?
$rows = $select->from(array('r'=>'report_tb'), array('rep_id', 'visit_id'))
->join(array('v'=>'visits_tb'), 'r.visit_id= v.visit_id', array('target'))
->where("r.visit_id=$id");
Have not tested the code, but looked more correct i my eyes, if you wanted to output all lines from the Report table, with a specified target.