Retrieve data using JOIN sql in Zend Framework 2 - php

I need to retrive data from 2 tables using join.
I have this code, but it fails with Call to undefined method Zend\Db\ResultSet\ResultSet::from():
public function getUsers($id){
$id = (int) $id;
$rowset = $this->tableGateway->select()->from(array('u' => 'user'))
->join(array('l' => 'levels'),
'u.user_id = l.id_user');
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
The SQL command would be:
select user.*,levels.name from user left join levels on user.user_id=levels.id_user
Thanks
UPDATE
Using #Mohamad changes I get:
The table name of the provided select object must match that of the table
My UsersTable.php looks like this now:
<?php
// module/Users/src/Users/Model/UsersTable.php:
namespace Users\Model;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;
class UsersTable
{
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
$select = new Select();
$select->from('levels');
$select->join('user', 'levels.id=user.user_id',Select::SQL_STAR,Select::JOIN_RIGHT);
$rowset = $this->tableGateway->selectWith ( $select );
$resultSet = $rowset->current();
if (!$resultSet) {
throw new \Exception("Could not find row $id");
}
return $resultSet;
}

i think you must pass two TableGetway to UserTable construct. you have to change Module.php
look this:
public function getServiceConfig()
{
return array(
'factories' => array(
'User\Model\UserTable' => function($sm) {
$userTableGateway = $sm->get('UserTableGateway');
$levelTableGateway = $sm->get('LevelTableGateway');
$table = new UserTable($userTableGateway,$levelTableGateway);
return $table;
},
'UserTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new User());
return new TableGateway('user', $dbAdapter, null, $resultSetPrototype);
},
'LevelTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Level());
return new TableGateway('level', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
then in your model:
protected $userTableGateway;
protected $levelTableGateway;
public function __construct($userTableGateway,$levelTableGateway)
{
$this->userTableGateway = $userTableGateway;
$this->levelTableGateway = $levelTableGateway;
}
public function fetchAll()
{
$select = new Select();
$select->from('levels');
$select->join('user', 'levels.id=user.user_id',Select::SQL_STAR,Select::JOIN_RIGHT);
$rowset = $this->levelTableGateway->selectWith ( $select );
$resultSet = $rowset->current();
if (!$resultSet) {
throw new \Exception("Could not find row $id");
}
return $resultSet;
}
i hope helped you

Related

zf2 tablegateway select columns with join table

I have this code (which works fine):
Class SsoRequserTable
public function fetchAll()
{
$select = new Select();
$select->from("sso_requser");
$select->join('sso_workunit', 'sso_workunit.sso_workunit_id = sso_requser.sso_workunit_id', array("unitname"), 'left');
echo $select->getSqlString();
$result = $this->tableGateway->selectWith($select);
return $result;
}
class SsoRequser
class SsoRequser{
public $sso_requser_id;
public $firstname;
public $lastname;
public $fullname;
public $sso_workunit_id;
public function exchangeArray($data){
$this->sso_requser_id = (!empty($data['sso_requser_id'])) ? $data['sso_requser_id'] : null;
$this->firstname = (!empty($data['firstname'])) ? $data['firstname'] : null;
$this->lastname = (!empty($data['lastname'])) ? $data['lastname'] : null;
$this->fullname = (!empty($data['fullname'])) ? $data['fullname'] : null;
$this->sso_workunit_id = (!empty($data['sso_workunit_id'])) ? $data['sso_workunit_id'] : null;
}
}
Module.php
public function getServiceConfig() {
return array(
'invokables' => array(
// 'Aclplugin' => 'Auth\Controller\Plugin\Aclplugin',
),
'factories' => array('SSO\Model\SsoRequserTable' => function($sm) {
$tableGateway = $sm->get('SsoRequserTableGateway');
$table = new SsoRequserTable($tableGateway);
return $table;
},
'SsoRequserTableGateway' => function ($sm) {
$dbAdapter = $sm->get('postgresql_adapter');
$resultSetPrototype = new HydratingResultSet();
$resultSetPrototype->setObjectPrototype(new SsoRequser());
return new TableGateway('sso_requser', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
But I can`t get the sso_workunit columns to work. I have read the Zend Documentation and nothing effectively worked for me. I need name to have an alias "unitname".
And i got the message error "Undefined property: SSO\Model\Entity\SsoRequser::$unitname "
Whether I should add unitname in class SsoRequser ?
Anyone can help me ?

Zend 2 - User session does not work

I'm having difficulty reading logged user's session in user model.
When retrieve user data from any other model it works perfectly.
MODULE.PHP
'session' => function ($sm) {
$config = $sm->get('config');
if (isset($config['session'])) {
$session = $config['session']['config']['options']['name'];
//Various Session options
$manager = new \Zend\Session\SessionManager();
if(filter_input(INPUT_SERVER, 'APPLICATION_ENV') === 'production'){
$manager->getConfig()
->setCookieHttpOnly(true)
->setCookieSecure(false);
$manager->start();
}
return new Session($session);
}
},
BaseTable.php
public function getIdentity($property = null) {
$storage = $this->getServiceLocator()->get('session');
if (!$storage) {
return false;
}
$data = $storage->read();
if ($property && isset($data[$property])) {
return $data[$property];
}
return $data;
}
When i call getIdentity function where tb_usuario instantiated I get this error:
Fatal error: Call to a member function get() on a non-object in
C:\wamp\www\sigaAvaliacoes\module\application\src\Application\Model\BaseTable.php
on line 73
Sorry my english, thanks!
Sorry guys, i found the problem, in Module.php i not instance serviceLocator:
'Usuario' => function($sm) {
$tableGateway = new TableGateway('tb_usuario', $sm->get('db_adapter_main'));
return new Model\Usuario($tableGateway);
},
Now work:
'Usuario' => function($sm) {
$tableGateway = new TableGateway('tb_usuario', $sm->get('db_adapter_main'));
$updates = new Model\Usuario($tableGateway);
$updates->setServiceLocator($sm);
return $updates;
},
Thanks =D

Getting Statement couldn't be produced with sql in zend2?

this is my function in my model:
public function user_login($getData,$session_id){ // manage the user's login
$email = $getData['login_email'];
$password = $getData['login_password'];
$select = $this->adapter->query("select count(*) as counter from users where email = '$email' and password = '".md5($password)."'");
$results = $select->execute();
if ($results->current()['counter'] == 1 ){
$update = $this->adapter->query("update users set session_id = '".$session_id."' where email = '".$email."'");
$update_session = $update->execute();
return 1;
}else{
return 0;
}
}
When I executed the count query it works and im also using this method to get values from queries or to insert data in db. but now i want to do a simple update, which does not work for some reason. I don't know why ? why i'm getting this message ?
UPDATE: this is the content of the Module.php file from my module name folder:
namespace Application;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
class Module
{
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getServiceConfig() {
return array(
'factories' => array(
'Application\Model\UsersTable' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new Model\UsersTable($dbAdapter);
return $table;
},
),
);
}
}
Had the same issue, found solution here.
Probably unbuffered query?
$statement = $adapter->query("SELECT ...");
$result = $statement->execute();
$result->buffer();
// validate your result

ZF2 count rows in database

Hi i have this problem: i want to count rows in ZF2 in database and i use this code in controller:
public function getProductTable()
{
if (!$this->productTable) {
$sm = $this->getServiceLocator();
$this->productTable = $sm->get('Product\Model\ProductTable');
}
return $this->productTable;
}
public function productCounter($user_id){
//product Count
$productCount = $this->getProductTable()->select(); // error reported on this line
return $productCount->from("product")->where(array('user_id' => $user_id))->count();
}
function getProductTable() is working because i use it on other lines. mistake is reported on marked line in code. Where is my mistake? .. Thanks for answers
Change the productCounter function to this
public function productCounter($user_id) {
return $this->getProductTable()->select(array('user_id' => $user_id))->count();
}
Select method returns the results right away, not the Select object.
I hope along with getProductTable() and productCounter() functions you also have the following constructor too;
protected $tableGateway;
.....
...
public function __construct(TableGateway $tableGateway) {
$this->tableGateway = $tableGateway;
}`
If so then try this -
public function productCounter($user_id) {
return $this->tableGateway->select(array('user_id' => $user_id))->count();
}
This should work fine.
Now if you don't have such a constructor then there is lot to be done if you want to use the TableGateway for executing the queries -
Have such a constructor first. //Important
In Product\Module.php -
'Product\Model\ProductTable' => function($sm) {
$tableGateway = $sm->get('ProductTableGateway');
$table = new ProductTable($tableGateway);
return $table;
},
'ProductTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Product());
return new TableGateway('product', $dbAdapter, null, $resultSetPrototype);
},
Now try that productCounter() function.
I hope it helps.

Execute In Query For ResultSet Zend Framework 2?

I want to get 3 separate row from 'cms' table.but all time i only got first row why?
My Cms.php page is:
<?php
namespace Front\Model;
use Zend\Db\TableGateway\AbstractTableGateway;
class Cms extends AbstractTableGateway {
public function __construct($adapter) {
$this->table = 'cms';
$this->adapter = $adapter;
}
public function getCmsContent($id){
$id = (int) $id;
$rowset = $this->select(array('id'=>$id));
if (!$row = $rowset->current()){
throw new \Exception ('Row not found');
}
return $row;
}
}
My Controller is :FrontController.php is:
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Front\Model\Cms;
use Front\Model\Setting;
use Front\Model\Slider;
class FrontController extends AbstractActionController
{
public function indexAction()
{
$this->layout()->slider_data = $this->getSlider()->fetchAll();
$this->layout()->setting_data = $this->getSetting()->getSettingContent(1);
return array('cms_data'=>$this->getCms()->getCmsContent('1,2,3'));
}
public function getSlider(){
return $this->getServiceLocator()->get('Front/Model/Slider');
}
public function getCms(){
return $this->getServiceLocator()->get('Front\Model\Cms');
}
public function getSetting(){
return $this->getServiceLocator()->get('Front/Model/Setting');
}
}
My Model is:
namespace Front;
class Module
{
public function getAutoloaderConfig()
{
return array('Zend\Loader\StandardAutoloader' =>
array('namespaces' =>
array(__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,),
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
// Add this method:
public function getServiceConfig()
{
return array(
'factories' => array(
'Front\Model\AlbumTable' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new \Front\Model\AlbumTable($dbAdapter);
return $table;
},
'Front\Model\Cms' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new \Front\Model\Cms($dbAdapter);
return $table;
},
'Front\Model\Setting' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new \Front\Model\Setting($dbAdapter);
return $table;
},
'Front\Model\Slider' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new \Front\Model\Slider($dbAdapter);
return $table;
},
),
);
}
}
?>
My View:index.php Page is:
<?php print_R($cms_data); ?>
try this code block and change the $condition according to you
public function getCmsContent($id){
$id = (int) $id;
$select = new Select();
$select->from(array('t' => $this->table))
->where(array($condition));
$statement = $this->adapter->createStatement();
$select->prepareStatement($this->adapter, $statement);
$result = $statement->execute();
$rows = array();
if ($result->count()) {
$rows = new ResultSet();
return $rows->initialize($result)->toArray();
}
}
You try:
class Cms extends AbstractTableGateway {
public function __construct($adapter) {
$this->table = 'cms';
$this->adapter = $adapter;
}
public function getCmsContent($id){
return $this->select(array(
new Expression('id IN (?)', array($id)),
));
}
}
Get contents
$contents = $this->getCms()->getCmsContent(array(1, 2, 3));
$results = array();
foreach($contents as $content){
$results[] = $content;
}
print_r($results);

Categories