S
S
Symbi0t2014-09-17 18:24:46
Zend Framework
Symbi0t, 2014-09-17 18:24:46

How to work with two tables in Zend Framework 2?

Greetings!
To work with models, a separate model file is created, for example, /Model/someTable.php.
Next, using the factory, we create a wrapper for working with this table:

'factories' => array(
                'Some\Model\SomeTable' => function($sm)
                {
      $dbAdapter = $sm->get('adapter');
      $tableGateway = new TableGateway('table', $dbAdapter);
      $table = new SomeTable($tableGateway);
                        return $table;
    },
        )

Thus it turns out that we are working with a specific table. But I need to get the contents of another table within the SomeTable class. Is it really necessary to create a separate model file and factory for this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Symbi0t, 2014-09-18
@Symbi0t

Found one solution.
In the factory, when creating a wrapper, pass the adapter to the class constructor (SomeTable) as the second argument:

'factories' => array(
                'Some\Model\SomeTable' => function($sm)
                {
      $dbAdapter = $sm->get('adapter');
      $tableGateway = new TableGateway('table', $dbAdapter);
      $table = new SomeTable($tableGateway, $dbAdapter);
                        return $table;
    },
        )

In order to be able to create separate sql queries within this class.
It turned out something like this:
namespace Some\Model;

use Zend\Db\Sql\Sql;
use Zend\Db\TableGateway\TableGateway;

class SomeTable
{
  protected $dbAdapter;
  protected $tableGateway;

  public function __construct(TableGateway $tableGateway, $dbAdapter)
        {
               $this->dbAdapter    = $dbAdapter;
               $this->tableGateway = $tableGateway;
        }

        public function someAction()
        {
          $sql = new Sql($this->dbAdapter);
    $select = $sql->select();
    $select->from('another_table');
    $select->where(array('id' => 1));

    $statement = $sql->prepareStatementForSqlObject($select);
    $results = $statement->execute();
    
    return ($results->count()) ? $results->current() : null;
         }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question