I have one tabel 'cms' when i call fetchAll() function which fetch all data fetch data with order by id desc means i want to pass orderby condition with 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); ?>
An excerpt from the manual:
$select = new Select;
$select->order('id DESC'); // produces 'id' DESC
$select = new Select;
$select->order('id DESC')
->order('name ASC, age DESC'); // produces 'id' DESC, 'name' ASC, 'age' DESC
$select = new Select;
$select->order(array('name ASC', 'age DESC')); // produces 'name' ASC, 'age' DESC
The same method order applies to table gateway.
Related
I followed every step of the Get Started tutorial on ZF2 website ( http://framework.zend.com/manual/current/en/user-guide/database-and-models.html ).
I've searched on this website (and google of course) possible solutions. I'm not gonna lie, there are thousands of questions that look like these EXCEPT all solution given don't seem to work.
These are the error codes : (sorry for the format)
( ! ) Fatal error: Class 'Action\Model\ActionTable' not found in C:\wamp\www\zf2\module\Action\Module.php on line 46
Module.php (under module/Action)
<?php
/**
* ZF2 uses ModuleManager to load and configure a module. To do that, it will look up for this class in the root of the module directory.
*/
namespace Action;
use Action\Model\ActionTable;
use Action\Model\Action;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
/**
* Class Module is expected by ZF2.
*/
class Module {
public function getAutoloaderConfig() {
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getConfig() {
return include __DIR__ . '/config/module.config.php';
}
public function getServiceConfig() {
return array(
'factories' => array(
'Action\Model\ActionTable' => function($sm) {
$tableGateway = $sm->get('ActionTableGateway');
$table = new ActionTable($tableGateway);
return $table;
},
'ActionTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Action());
return new TableGateway('action', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
}
?>
ActionTable.php (under module/Action/src/Action/Model)
<?php
namespace Action\Model;
use Zend\Db\TableGateway\TableGateway;
class AlbumTable
{
protected $tableGateway;
/**
* TableGateway is an object that represents a table in a database.
*/
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
/**
* fetchAll function
* retrieves all rows from the database
* #return ResultSet containing all rows of the database.
*/
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}
/**
* getAction function
* retrieves a single row from the database using the id
* #param $id (int)
* #return $row of error in exception
*/
public function getAction($id)
{
$id = (int) $id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
/**
* saveAction function
* Creates a new row in the database or updates a row that already exists
* #param Action
* print Exception if error
*/
public function saveAction(Action $action)
{
$data = array(
'Num_action'=> $action-> $act_num,
'libelle_action'=> $action-> $act_label,
);
$id = (int) $action->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getAction($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Action id does not exist');
}
}
}
/**
* deleteAction function
* removes a row completely
* #param $id
*/
public function deleteAction($id)
{
$this->tableGateway->delete(array('id' => (int) $id));
}
}
?>
The architecture is good, the file are at the place they are said to be, i've tried adding \Action\Model\ before the ActionTable($tableGateway)...
Nothing seems to work.
Anyone as any idea ??
Thank you very much for ANY clue, ANY lead, you could give me.
In ActionTable.php on line 6:
class AlbumTable
presumably should be
class ActionTable
everything else looks good.
AR model Player:
public function scopes()
{
return array(
'proleague' => array(
'condition' => 'mode = "proleague"',
),
'main' => array(
'condition' => 'mode = "main"',
),
);
}
Using model Player:
Player::model()->
proleague()->
with('startposition')->
findAllByAttributes(... here some condition ...);
^^^ That's all ok. Scope-condition will be executed. But...
In my project I have many places where any scope for Player model doesn't specified and in this cases I need use this scope-condition as default:
'main' => array(
'condition' => 'mode = "main"',
)
If I add defaultScope() method to Player model like this
public function defaultScope()
{
return array(
'condition' => 'mode = "main"',
);
}
the next code
Player::model()->
proleague()->
with('startposition')->
findAllByAttributes(... here some condition ...);
won't run correct. I won't get mode = "proleague" condition, becouse I'll use defaultScope() with mode = "main".
Any suggestions? How can I resolve the problem?
You should just use the resetScope(true) method. It "removes" the defaultScope filter.
$model = Player::model()->resetScope(true)->proleague();
create a new Class for this.
<?php
## e.g. protected/models/
class MyCoreAR extends CActiveRecord
{
/**
* Switch off the default scope
*/
private $_defaultScopeDisabled = false; // Flag - whether defaultScope is disabled or not
public function setDefaultScopeDisabled($bool)
{
$this->_defaultScopeDisabled = $bool;
}
public function getDefaultScopeDisabled()
{
return $this->_defaultScopeDisabled;
}
public function noScope()
{
$obj = clone $this;
$obj->setDefaultScopeDisabled(true);
return $obj;
}
// see http://www.yiiframework.com/wiki/462/yii-for-beginners-2/#hh16
public function resetScope($bool = true)
{
$this->setDefaultScopeDisabled(true);
return parent::resetScope($bool);
}
public function defaultScope()
{
if(!$this->getDefaultScopeDisabled()) {
return array(
'condition' => 'mode = "main"',
);
} else {
return array();
}
}
}
In your code:
// no default scope
$model = Player::model()->noScope()->proleague();
// with default scope
$model = Player::model()->proleague();
I want to list on a view something like
Number Commands | Date of commands | Description (text from table article)
All I have is
Number Commands | Date of commands | Description (id from table Bc)
I have two tables: BC (as commands) which have columns: id_commands, id_article, id_user, number_commands, date_commands, ...
and table Article which have columns : id_article, name_article, description_article, ...
According to this tutorial, How to extend the ZF2 skeleton application - entities with foreign keys
There are my codes:
On Bc\Model\Bc.php
class Bc implements BcInterface
{
...
public function setArticle(ArticleInterface $bc_article)
{
$this->article = $bc_article;
}
public function getArticle()
{
return $this->bc_article;
}
}
On Bc\Mapper\BcHydrator.php
namespace Bc\Mapper;
class BcHydrator // extends Zend\Stdlib\Hydrator\ClassMethods
{
public function extract($object)
{
return array(
'bc_id' => $object->getBc_id(),
'article_designation' => $object->getA_designation(),
'article_reference' => $object->getA_reference()
);
}
}
On Bc\Mapper\ZendDbSqlMapper.php
...
public function findAllWithArticle()
{
$sql = new Sql($this->dbAdapter);
$select = $sql -> select()
-> from( array('a'=>'s_article'))
-> join( array('bc' => 's_bc'),
'bc.bc_id_article = a.a_id');
$stmt = $sql->prepareStatementForSqlObject($select);
$result = $stmt->execute();
if ($result instanceof ResultInterface && $result->isQueryResult()) {
$resultSet = new HydratingResultSet($this->hydrator, $this->bcPrototype);
\Zend\Debug\Debug::dump($result);die();
//return $resultSet->initialize($result);
}
return array();
}
On my Controller
...
public function detailAction()
{
$id = $this->params()->fromRoute('id');
try {
//$bc = $this->bcService->findBc($id);
$bc = $this->bcService->findAllBcsWithArticle($id);
$articleDesignation = $bc->getArticle()->getA_designation();
} catch (\InvalidArgumentException $ex) {
return $this->redirect()->toRoute('bc');
}
return new ViewModel(array(
'bc' => $bc,
'article' => $articleDesignation
));
}
I have this error, when I have access to my view:
Fatal error: Call to undefined method
Zend\Db\ResultSet\HydratingResultSet::getArticle()
Did someone have an idea of what I did wrong?
Finally i found a solution for those who want to know.
I didn't use hydrator, but i have the result i want.
Add on my class Bc (Bc\Model\Bc.php) a protected variable $description and set setter and getter.
On my Mapper (Bc\Mapper\ZendDbSqlMapper.php), i added a function findContent ($id), and use as sql request:
$sql = new Sql($this->dbAdapter); $select = $sql -> select()
-> from( array('bc'=>'bc'))
-> join( array('a' => 'article'),
'bc.bc_id_article = a.id',
array(
'description' => 'description',
));
$select->where(array('bc_id = ?' => $id));
On my service (Bc\Service\BcService.php)
public function findBcsContent($id)
{
return $this->bcMapper->findContent($id);
}
And on my controller
public function indexAction()
{
return new ViewModel(array(
'bcs'=> $this->bcService->findAllBcsContent()
));
}
On my view, i could use
$this->escapeHtml($bc->getDesignation());
That's all
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);
}
I would like to do a simple INNER JOIN between two tables in Zend2.
Concretely, I would like to do this in Zend2:
SELECT * FROM foo, bar WHERE foo.foreign_id = bar.id;
I have a FooTable:
class FooTable
{
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function get($id)
{
$rowset = $this->tableGateway->select(function (Select $select) {
$select->from('foo');
});
}
}
The $select->from('foo'); returns an error:
==> Since this object was created with a table and/or schema in the constructor, it is read only.
So, I can't tweak my FROM statement to match a simple inner join between FooTable and BarTable.
I hope this will help you along your journey as this is a working example I have:
namespace Pool\Model;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Sql\Select;
class IpaddressPool extends AbstractTableGateway
{
public function __construct($adapter)
{
$this->table = 'ipaddress_pool';
$this->adapter = $adapter;
$this->initialize();
}
public function Leases($poolid)
{
$result = $this->select(function (Select $select) use ($poolid) {
$select
->columns(array(
'ipaddress',
'accountid',
'productid',
'webaccountid'
))
->join('account', 'account.accountid = ipaddress_pool.accountid', array(
'firstname',
'lastname'
))
->join('product_hosting', 'product_hosting.hostingid = ipaddress_pool.hostingid', array(
'name'
))
->join('webaccount', 'webaccount.webaccountid = ipaddress_pool.webaccountid', array(
'domain'
))->where->equalTo('ipaddress_pool.poolid', $poolid);
});
return $result->toArray();
}
}