Reputation: 545
I new in ZF and have a code located below. I try get custom colums and join in sql select, but it failed. I tried to use the search but found no results. Tell me examples of how to do more complex queries. Thanks.
<?php
namespace FcFlight\Model;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Select;
use FcFlight\Filter\FlightHeaderFilter;
class FlightHeaderModel extends AbstractTableGateway
{
/**
* @var string
*/
protected $table = 'flightBaseHeaderForm';
/**
* @param \Zend\Db\Adapter\Adapter $adapter
*/
public function __construct(Adapter $adapter)
{
$this->adapter = $adapter;
$this->resultSetPrototype = new ResultSet();
$this->resultSetPrototype->setArrayObjectPrototype(new FlightHeaderFilter($this->adapter));
$this->initialize();
}
/**
* @param $id
* @return array|\ArrayObject|null
* @throws \Exception
*/
public function get($id)
{
$id = (int)$id;
$rowSet = $this->select(array('id' => $id));
$row = $rowSet->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
$row->dateOrder = date('Y-m-d', $row->dateOrder);
return $row;
}
}
Upvotes: 2
Views: 1607
Reputation: 2586
Since you are using the tableGateway, you must get an instance of Sql(): $this->getSql();
With that instance you will create an instance of Select, which will then let you perform a join:
$sql = $this->getSql();
$select = $sql->select();
$select->join('TableNameToJoin', 'MainColumnA = JoinColumnA');
Then to execute the query, you call selectWith on your tableGateway:
$this->selectWith($select);
If you wish to customize the join further, you can pass two more arugments:
You can also add an alias to the table you are joining on by passing an Array as the table name, with the key
of the array being the alias and the value
being the table name.
$select->join(['Alias' => 'TableNameToJoin'], 'MainColumnA = Alias.JoinColumnA', ['ColumnA', 'ColumnB'], $select::JOIN_LEFT);
Upvotes: 4