简体   繁体   中英

Execute Query with Where Condition For ResultSet Zend Framework 2?

I have one tabel 'cms' which include cms page with 3 separate parent category(type) . when i call fetchAll() function which fetch all data but i want to only fetch data which parent category(type)='1' means i want to pass where condition and orderby condition in fetchAll() function.

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 fetchAll($id) {
               return $this->select();
        }
        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()
    {   

        return        array('cms_data'=>$this->getCms()->fetchAll('1'));             
    }

    public function getCms(){
        return $this->getServiceLocator()->get('Front\Model\Cms');
    }

}

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\Cms' =>  function($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $table     = new \Front\Model\Cms($dbAdapter);
                    return $table;
                },

            ),
        );
    }
}
?>

My View:index.php Page is:

 <?php print_R($cms_data); ?>

Your question is not clear. Are you asking how to add Where clause to your query? If so, then this is it:

use Zend\Db\Sql\Predicate\Operator;

public function fetchAll($id) {

   return $this->select()
        ->where(new Operator('type', Operator::OPERATOR_EQUAL_TO, $id);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM