Inner join in Zend framework

2019-05-29 15:56发布

I want to make inner join between two tables

Visit table has

  • visit_id
  • target

Report table has

  • rep_id
  • visit_id

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

4条回答
趁早两清
2楼-- · 2019-05-29 16:29
    $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);
查看更多
叛逆
3楼-- · 2019-05-29 16:29

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.

查看更多
Fickle 薄情
4楼-- · 2019-05-29 16:37

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();
查看更多
贪生不怕死
5楼-- · 2019-05-29 16:44

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();
}
查看更多
登录 后发表回答