I hope I'm asking this question in an understandable way. I've been working on an app that has been dealing with 1 table ( jobschedule ). So, I have models/Jobschedule.php, models/JobscheduleMapper.php, controllers/JobscheduleController.php, view/scripts/jobschedule/*.phtml files
So in my controller I'll do something like this:
$jobnumber = $jobschedule->getJobnum();
$jobtype = $jobschedule->getJobtype();
$table = $this->getDbTable();
public function listAction()
{
$this->_helper->layout->disableLayout();
$this->view->jobnum = $this->getRequest()->getParam( 'jobnum', false );
$this->view->items = array();
$jobschedule = new Application_Model_Jobschedule();
$jobschedule->setJobnum( $this->view->jobnum );
$mapper = new Application_Model_JobscheduleMapper();
$this->view->entries = $mapper->fetchAll ( $jobschedule );
}
and then in my mapper I I do something like:
$resultSet = $table->fetchAll($table->select()->where('jobnum = ?', $jobnumber)->where('jobtype = ?', $jobtype) );
$entries = array();
foreach ($resultSet as $row) {
$entry = new Application_Model_Jobschedule();
$entry->setJobnum($row->jobnum)
->setJobtype($row->jobtype)
->setJobdesc($row->jobdesc)
->setJobstart($row->jobstart)
->setJobend($row->jobend)
->setJobfinished($row->jobfinished)
->setJobnotes($row->jobnotes)
->setJobid($row->jobid);
$entries[] = $entry;
}
return $entries;
}
Then in my view I can manipulate $entries. Well, the problem I'm coming across now is that there is also another table called 'jobindex' that has a column in it called 'jobno'. That 'jobno' column holds the same record as the 'jobnum' column in the 'jobschedule' table. I need to find the value of the 'store_type' column in the 'jobindex' table where jobindex.jobno = joschedule.jobnum ( where 1234 is the jobno/jobnum for example ). Can someone please help me here? Do I need to create a jobindex mapper and controller? If so, that's done ... I just don't know how to manipulate both tables at once and get the record I need. And where to put that code...in my controller?
If I understand you correctly this is the SQL query you need to extract the data from database:
SELECT `jobschedule`.* FROM `jobschedule` INNER JOIN `jobindex` ON jobindex.jobno = jobschedule.jobnum WHERE (jobindex.jobtype = 'WM')
Assembling this SQL query in Zend would look something like this:
$select->from('jobschedule', array('*'))
->joinInner(
'jobindex',
'jobindex.jobno = jobschedule.jobnum',
array())
->where('jobindex.jobtype = ?', $jobtype);
Let us know if that's what you are looking for.
If I'm understanding you correctly, you'll want to join the 'jobindex' table to the 'jobschedule' table.
...
$resultSet = $table->fetchAll(
$table->select()->setIntegrityCheck(false)
->from($table, array('*'))
->joinLeft(
'jobindex',
'jobindex.jobno = jobschedule.jobnumber',
array('store_type'))
->where('jobnum = ?', $jobnumber)
->where('jobtype = ?', $jobtype)
->where('jobindex.store_type = ?', $_POST['store_num'])
);
....
Depending on how 'jobschedule' is related to 'jobindex', you may want an inner join (joinInner()) instead.
The setIntegrityCheck(false) disables referential integrity between the tables, which is only important if you are writing to them. For queries like this one, you can just disable it and move on (else it will throw an exception).
Related
I appreciate that this may not be possible, but is there a way to make Zend Paginate go to a specific item (record)?
The result I would like would allow me to seek a specific record in a tabled list of results, and display the appropriate page (within all available pages) combined with a name anchor tag to display the specific record.
To clarify: If I had the results as a Zend_Db_Table_Rowset_Abstract I would use the seek() method in a similar fashion to $rowset->seek(8); Although I don't believe the result returned by the DbSelect adapter is a SeekableIterator?
The code within my Mapper (using the Table Data Gateway pattern):
public function paginate($where = array(), $order = null)
{
$select = $this->getDbTable()->select()->from($this->getTableName(), $this->getTableFields());
foreach ($where as $key => $value) {
$select->where($key, $value);
}
$select->order($order);
$adapter = new Zend_Paginator_Adapter_DbSelect($select);
$paginator = new Zend_Paginator($adapter);
return $paginator;
}
Within my controller:
$cache_id = sha1('list');
$mapper = new Application_Model_Galleries_Mapper();
if(!($data = Zend_Registry::get('cache')->load($cache_id))) {
$data = $mapper->paginate(array(), $sort);
Zend_Registry::get('cache')->save($data, $cache_id, array('list'), 7200);
}
$data->setCurrentPageNumber($this->_getParam('page'));
$data->setItemCountPerPage(30);
$this->view->paginator = $data;
To return a Zend_Paginator with a seekable iterator (Zend_Db_Table_Rowset) use the Zend_Paginator_Adapter_DbTableSelect() as it returns a rowset object, as opposed to Zend_Paginator_Adaoter_DbSelect() which returns an array().
Zend_Paginator
How would I write an Zend DB query to select all from the column ID?
So far I have tried:
public function getLatestUserID()
{
$ids = $this->select()
->where('id = ?');
return $ids;
}
But to no avail.
You just want the id column,
You failed to call an execute command.
try:
//assuming you are using a DbTable model
public function getLatestUserID()
{
$ids = $this->fetchAll('id');
return $ids;
}
I would do it like this, because I use the select() object for everything:
public function getLatestUserID()
{
$select = $this->select();
//I'm not sure if $this will work in this contex but you can out the table name
$select->from(array($this), array('id'));
$ids = $this->fetchAll($select);
return $ids;
}
The first two examples should return just the id column of the table, now if you actually want to query for a specific id:
public function getLatestUserID($id)
{
$select = $this->select();
$select->where('id = ?', $id);
//fetchAll() would still work here if we wanted multiple rows returned
//but fetchRow() for one row and fetchRowset() for multiple rows are probably
//more specific for this purpose.
$ids = $this->fetchRow($select);
return $ids;
}
make sure your class containing getLatestUserID does extend Zend_Db_Table_Abstract also :
$ids = $this->select()->where('id = ?'); can't work because where('id = ?'); expects an id value like where('id = ?', $id);
if what you want is the latest inserted row's Id use :
$lastInsertId = $this->getAdapter()->lastInsertId();
(however if you are using an oracle database this will not work and you should use $lastInsertId = $this->getAdapter()->lastSequenceId('USER_TABLE_SEQUENCE'); )
I have a number of FilteringSelect elements within my Zend Framework application that are working fine but they are based on simple queries.
I now need to create a FilteringSelect that will allow me to select the id of one table while displaying the text of field in a related table, i.e. I have two tables groomservices and groomprocedures which are related (i.e. groomprocedures.groomProceduresID has many groomservices.procedure).
The form I'm trying to create is for an appointments table which has many groomservices.groomServicesID values. I want the user to be able to see the name of the procedure while saving the value of the groomservices.groomServicesID using the FilteringSelect.
So far I've not been able to do this in that my FilteringSelect displays nothing, I'm sure this can be done just that the fault is with my inexperience with Zend,Doctrine and Dojo
I'm not sure if my problem is with my autocomplete action(including the query) or with the FilteringSelect element.
Can anyone spot where I've gone wrong in the code sections below, I need to get this working.
My autocomplete action within my controller
public function gserviceAction()
{
// disable layout and view rendering
$this->_helper->layout->disableLayout();
$this->getHelper('viewRenderer')->setNoRender(true);
// get a list of all grooming services IDs and related procedures
$qry= Doctrine_Query::create()
->select('g.groomServicesID,p.groomProcedure')
->from('PetManager_Model_Groomservices g')
->leftJoin('g.PetManager_Model_Groomprocedures p');
$result=$qry->fetchArray();
//generate and return JSON string
$data = new Zend_Dojo_Data('g.groomServicesID',$result);
echo $data->toJson();
}
My FilteringSelect element code
// Create a autocomplete select input for the service
$gservice = new Zend_Dojo_Form_Element_FilteringSelect('gapmtService');
$gservice->setLabel('Proceedure');
$gservice->setOptions(array(
'autocomplete' => true,
'storeID' => 'gserviceStore',
'storeType' => 'dojo.data.ItemFileReadStore',
'storeParams' => array('url' => "/groomappointments/appointment/gservice"),
'dijitParams' => array('searchAttr' => 'groomProcedure')))
->setRequired(true)
->addValidator('NotEmpty', true)
->addFilter('HTMLEntities')
->addFilter('StringToLower')
->addFilter('StringTrim');
Many thanks in advance,
Graham
P.S. orgot to mention I tried the following query in mysql and I gave me what I'm looking for I believe the Doctine query evaluates to the same.
select groomservices.groomservicesID,groomprocedures.groomprocedure from groomprocedures left join groomservices on groomprocedures.groomproceduresID =groomservices.groomProcedure
But I'm not sure if I formatted the query correctly in Doctrine.
EDIT in relation to the flammon's comments
Ok I've set the code to the following but I'm still not getting anything to display.
public function gserviceAction()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContexts(array(
'gservice' => 'json'
));
// get a list of all grooming services IDs and related procedures
$qry= Doctrine_Query::create()
->select('g.groomServicesID AS id,p.groomprocedure AS name')
->from('PetManager_Model_Groomservices g')
->leftJoin('g.PetManager_Model_Groomprocedures p');
$this->view->model = (object) array();
$this->view->model->identifier = 'id';
$this->view->model->label = 'name';
$this->view->model->items = array();
$tableRows = $this->dbTable->fetchAll($qry);
foreach ($tableRows as $row) {
$this->view->model->items[] = $row->toArray();
}
}
I'm sure the fault lies with me.
It looks like there's a problem with the data that you're putting in the ItemFileReadStore.
Here are a few pointers.
Consider extending Zend_Rest_Controller for your services. It'll be easier to manage your contexts and your views. You'll be able to do something like this:
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContexts(array(
'gservice' => 'json'
));
}
And it will eliminate the need for the following in each of you service actions.
// disable layout and view rendering
$this->_helper->layout->disableLayout();
$this->getHelper('viewRenderer')->setNoRender(true);
You'll need to either pass the format parameter or use the following plugin to help with the context switch. Passing the format parameter is simpler but it pollutes the url with ?format=json. Here's the Zend documentation on AjaxContext.
Here's a plugin that you can use if you don't want to pass the format parameter.
class Application_Plugin_AcceptHandler extends Zend_Controller_Plugin_Abstract
{
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
if (!$request instanceof Zend_Controller_Request_Http) {
return;
}
$header = $request->getHeader('Accept');
switch (true) {
case (strstr($header, 'application/json')):
Zend_Registry::get('logger')->log('Setting format to json', Zend_Log::INFO);
$request->setParam('format', 'json');
break;
case (strstr($header, 'application/xml')
&& (!strstr($header, 'html'))):
Zend_Registry::get('logger')->log('Setting format to xml', Zend_Log::INFO);
$request->setParam('format', 'xml');
break;
default:
Zend_Registry::get('logger')->log('Setting format to html', Zend_Log::INFO);
break;
}
}
}
In your controller, instead of echoing the data, create view variables that dojo expects. See this document for the format.
$this->view->model = (object) array();
$this->view->model->identifier = 'id';
$this->view->model->label = 'name';
$this->view->model->items = array();
In your controller, fetch your table rows:
$tableRows = $this->dbTable->fetchAll($select);
or, if you've put model code in a function, it might look more like:
$tableRows = $this->dbTable->fetchGroomProcedures();
Put your row data in the model->items[] array:
foreach ($tableRows as $row) {
$this->view->model->items[] = $row->toArray();
}
Create a view, view/scripts/appointment/gservice.json.phtml and in it put
Zend_Json::encode($this->model)
Use Firebug to see what is returned from your service.
I have the following code inside a class that extends Zend_Db_Table_Abstract:
public function fetchByFriends($id) {
/*
* SELECT * FROM list
* INNER JOIN friendship ON
* list.user_id = friendship.friend_id
* WHERE friendship.user_id = ?
*/
$select = $this->select()
->from("list")
->join("friendship", "list.user_id = friendship.friend_id")
->where("friendship.user_id = ?", $id);
$select->setIntegrityCheck(false); // allows joins within a DbTable
$stmt = $select->query();
return $this->fetchAll($stmt);
}
While the query works fine the data returned is of an array. Is there some way to refactor this so that fetchAll returns it as a Zend_Db_Table_Rowset, rather than an array?
Poor research on my part. I found the answer in Zend's reference manual:
Advanced usage
Example #27 Using a lookup table to refine the results of fetchAll()
$table = new Bugs();
// retrieve with from part set, important when joining
$select = $table->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
$select->setIntegrityCheck(false)
->where('bug_status = ?', 'NEW')
->join('accounts', 'accounts.account_name =
bugs.reported_by')
->where('accounts.account_name = ?', 'Bob');
$rows = $table->fetchAll($select);
Does anyone know of a way to group where clauses with Zend_Db? Basically I have this query
$sql = $table->select()
->where('company_id = ?', $company_id)
->where('client_email = ?', $client_email)
->orWhere('client_email_alt = ?', $client_email);
Which is giving me this:
SELECT `clients`.* FROM `clients` WHERE (company_id = '1') AND (client_email = 'email#address.com') OR (client_email_alt = 'email#address.com')
But I need it to give me this, where the OR statement is grouped:
SELECT `clients`.* FROM `clients` WHERE (company_id = '1') AND ((client_email = 'email#address.com') OR (client_email_alt = 'email#address.com'))
In order to achieve this, you have to construct the grouped clause within a single call to the where method.
If both values of conditions are the same, you can do this:
$select->where('client_email = ? OR client_email_alt = ?', $client_email)
If there are multiple placeholders within the string, the DB adapter's quoteInto method will replace all placeholders with the provided value.
If you need to group an OR with different values for each field, you have to manually quote the values. It's a bit more complex:
$select->where(
$db->quoteInto('client_email = ?', $email1) . ' OR ' . $db->quoteInto('client_email_alt = ?', $email2)
); // $db is your instance of Zend_Db_Adapter_*
// You can get it from a Zend_Db_Table_Abstract
//subclass by calling its getAdapter() method
You can use getPart() to get WHERE statement and then connect sub-queries.
$select->where('client_email = ?', $client_email)
->orWhere('client_email_alt = ?', $client_email);
$subquery = $select->getPart(Zend_Db_Select::WHERE);
$select ->reset(Zend_Db_Select::WHERE);
$select ->where('company_id = ?', $company_id)
->where(implode(' ',$subquery));
For Zend Framework Version 2, things differ a bit:
See http://framework.zend.com/apidoc/2.2/classes/Zend.Db.Sql.Predicate.Predicate.html#nest
$table->select()
->where(['company_id'=> $company_id])
->nest
->where('client_email = ?', $client_email)
->or
->where('client_email_alt = ?', $client_email)
->unnest();
works fine and feels much cleaner than the ZF1 methods.
I needed to combine AND/OR statements but including OR statements conditionally, adding them only in some cases. This solution is an adaptation of what I did, based on small modifications of the accepted answer.
$sql = $table->select()
->where('company_id = ?', $company_id);
$orWhereClauses = [];
// We could add a conditional statement to add this statement
$orWhereClauses[] = $db->quoteInto('client_email = ?', $email1);
// Same applies to this statement
$orWhereClauses[] = $db->quoteInto('client_email_alt = ?', $email2);
$sql->where(implode(" OR ", $orWhereClauses));
In first you can generate subquery, then get "WHERE" part and insert into main query
$subquery = $db->select();
$subquery->orWhere('a>10');
$subquery->orWhere('b<20');
etc..
$subquery = $subquery->getPart(Zend_Db_Select::WHERE);
$select->where(implode(' ',$subquery));