I want to retrieve the id of the last inserted row. This is the code I use in the mapper:
public function save(Application_Model_Projects $project)
{
$data = array(
'id_user' => $project->getIdUser(),
'project_name' => $project->getProjectName(),
'project_description' => $project->getProjectDescription(),
'due_date' => $project->getDueDate(),
'id_customer' => $project->getIdCustomer()
);
if(($id = $project->getId()) === null) {
unset($data['id']);
$this->getDbTable()->insert($data);
return $this->getDbTable()->lastInsertId();
}else {
$this->getDbTable()->update($data, array('id = ?', (int) $id));
return $id;
}
}
According to the code above, it should return the id of the object. It is either the id after insertion or the current id.
The code where I use this function:
$currentUser = new Application_Model_UserAuth();
$project = new Application_Model_Projects();
$project->setProjectName($formValues['projectName'])
->setProjectDescription($formValues['projectDescription'])
->setDueDate(date("Y-m-d",strtotime($formValues['dueDate'])))
->setIdCustomer($formValues['assignCustomer'])
->setIdUser($currentUser->id);
$projectMapper = new Application_Model_ProjectsMapper();
$idProject = $projectMapper->save($project);
The error I get is:
Fatal error: Call to undefined method Application_Model_DbTable_Projects::lastInsertId()
What is wrong with this? Shouldn't that return the last id? Because it is triggered upon insertion. In another sequence of code I call the lastInsertId: $Zend_Db_Table::getDefaultAdapter()->lastInsertId(). The only difference is that now I call lastInsertIt on a dbTable, that extends Zend_Db_Table_Abstract.
The answer to my question above is that I should call getAdapter() before lastInsertId().
Updated code:
if(($id = $project->getId()) === null) {
unset($data['id']);
$this->getDbTable()->insert($data);
return $this->getDbTable()->getAdapter()->lastInsertId();
}
If it is an single-column Primary Key the return value is lastInsertId by default, so you also can use this:
return $this->getDbTable()->insert($data);
Related
I am trying to follow the tutorial https://framework.zend.com/manual/2.4/en/user-guide/database-and-models.html
I have the problem, that i can't use the getAlbum(1) function.
It is possible to fetchAll() -> All rows returned
If I want to use getAlbum($personalnummer) -> Could not find row 1
Yes, there is an entry with Personalnummer 1 in the database and it is type int. The only difference is that, I use a Microsoft SQL Server, but the Configuration is right because all rows could be returned.
Any ideas?
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function getAlbum($personalnummer)
{
$personalnummer = (int) $personalnummer;
$rowset = $this->tableGateway->select(array('Personalnummer' => $personalnummer));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $personalnummer");
}
return $row;
}
try this if it helps replace
$rowset = $this->tableGateway->select(array('Personalnummer' => $personalnummer));
with this
$where = new \Zend\Db\Sql\Where();
$where->equalTo('Personalnummer', $personalnummer);
$rowset = $this->tableGateway->select($where)
I am trying to look up record using if I have the key then use Find if not use Where
private ApplicationDbContext db = new ApplicationDbContext();
public bool DeactivatePrice(int priceId = 0, string sponsorUserName = "")
{
var prices = db.BeveragePrices;
// if we have an id then find
if (priceId != 0)
{
prices = prices.Find(priceId);
}
else
{
prices = prices.Where(b => b.UserCreated == sponsorUserName);
}
if (prices != null)
{
// do something
}
return true;
I get the following error for
prices = prices.Find(priceId);
Cannot convert app.Model.BeveragePrices from system.data.entity.dbset
I am copying the pattern from this answer but something must be different.
Seems you forgot to put a predicate inside the Find function call. Also you need to do ToList on the collection. The second option is a lot more efficient. The first one gets the whole collection before selection.
Another note commented by #Alla is that the find returns a single element. So I assume another declaration had been made for 'price' in the first option I state down here.
price = prices.ToList.Find(b => b.PriceId == priceId);
Or
prices = prices.Select(b => b.PriceId == priceId);
I assume the field name is PriceId.
I am facing a problem. I have got following error "Fatal error: Call to a member function loadByOption() on a non-object in /var/www/Joomla/administrator/components/com_vodes/models/config.php on line 58". I am using Joomla 3.3.3 . I have upgraded it from 1.5 to 3.3.3
function save()
{
// initialize variables.
$table = JTable::getInstance('component');
$params = JRequest::getVar('params', array(), 'post', 'array');
$row = array();
$row['option'] = 'com_vodes';
$row['params'] = $params;
// load the component data for com_ajaxregister
if (!$table->loadByOption('com_vodes')) {
$this->setError($table->getError());
return false;
}
// bind the new values
$table->bind($row);
// check the row.
if (!$table->check()) {
$this->setError($table->getError());
return false;
}
// store the row.
if (!$table->store()) {
$this->setError($table->getError());
return false;
}
return true;
}
Please help to sought it out.
$table = JTable::getInstance('component');
you are passing the wrong parameter in your getInstance function the getInstance function returns null which makes the $table variable a non-object because it has no value. use your component name in setting the parameter.
When i run this code
public PartialViewResult GetHardware()
{
IQueryable<Hardware> hardware = db.Hardwares;
HardwareState hwState = new HardwareState();
IQueryable<IGrouping<string, Hardware>> groupByCategory = hardware.GroupBy(g => g.Category);
foreach (IGrouping<string, Hardware> group in groupByCategory)
{
hwState.GroupName = group.Key;
hwState.GroupUnitsCount = group.Count();
hwState.StorageReservedCount
= group.Where(m =>
m.Place.IsStorage == true &&
m.PlaceID != (int)Constants.HardwareState.Created &&
m.HardwareState == (int)Constants.HardwareState.Reserved).Count();
}
return PartialView(hwState);
}
I get an error about that the navigation property m.Place = null
when i transfer some of the text with the code of the foreach block
public PartialViewResult GetHardware()
{
IQueryable<Hardware> hardware = db.Hardwares;
HardwareState hwState = new HardwareState();
IQueryable<IGrouping<string, Hardware>> groupByCategory = hardware.GroupBy(g => g.Category);
hwState.StorageReservedCount
= hardware.Where(m =>
m.Place.IsStorage == true &&
m.PlaceID != (int)Constants.HardwareState.Created &&
m.HardwareState == (int)Constants.HardwareState.Reserved).Count();
foreach (IGrouping<string, Hardware> group in groupByCategory)
{
hwState.GroupName = group.Key;
hwState.GroupUnitsCount = group.Count();
}
return PartialView(hwState);
}
,the navigation property is not set to null and the error does not appear
Extension methods such as .AsQueryable or Include(x => x.Place) do not help me
How can i solve this problem?
UPDATE: If i change the type to IEnumerable instead IQueryable it begins to work!
but i would like to work with the IQueryable type
UPDATE2: I'm sorry, i did not put it correctly when i wrote that the error is an empty navigation property. Error that appears in fact
"There is already an open DataReader associated with this Command which must be closed first."
As described in this answer it is because: (quote)
"Another scenario when this always happens is when you iterate through
result of the query (IQueryable) and you will trigger lazy loading for
loaded entity inside the iteration."
But it does not say how to solve the problem without using ToList () or MARS
I have a many to many relation between Product and Properties. I'm using embedRelation() in my Product form to edit a Product and it's Properties. Properties includes images which causes my issue. Every time I save the form the updated_at column is updated for file properties even when no file is uploaded.
Therefore, I want to exclude empty properties when saving my form.
I'm using Symfony 1.4 and Doctrine 1.2.
I'm thinking something like this in my ProductForm.class.php, but I need some input on how to make this work.
Thanks
class ProductForm extends BaseProductForm
{
public function configure()
{
unset($this['created_at'], $this['updated_at'], $this['id'], $this['slug']);
$this->embedRelation('ProductProperties');
}
public function saveEmbeddedForms($con = null, $forms = null)
{
if (null === $forms)
{
$properties = $this->getValue('ProductProperties');
$forms = $this->embeddedForms;
foreach($properties as $p)
{
// If property value is empty, unset from $forms['ProductProperties']
}
}
}
}
I ended up avoiding Symfony's forms and saving models instead of saving forms. It can be easier when playing with embedded forms. http://arialdomartini.wordpress.com/2011/04/01/how-to-kill-symfony%E2%80%99s-forms-and-live-well/
Solved it by checking if posted value is a file, and if both filename and value_delete is null I unset from the array. It might not be best practice, but it works for now.
Solution based on http://www.symfony-project.org/more-with-symfony/1_4/en/06-Advanced-Forms
class ProductPropertyValidatorSchema extends sfValidatorSchema
{
protected function configure($options = array(), $messages = array())
{
// N0thing to configure
}
protected function doClean($values)
{
$errorSchema = new sfValidatorErrorSchema($this);
foreach($values as $key => $value)
{
$errorSchemaLocal = new sfValidatorErrorSchema($this);
if(array_key_exists('value_delete', $values))
{
if(!$value && !$values['value_delete'])
{
unset($values[$key]);
}
}
// Some error for this embedded-form
if (count($errorSchemaLocal))
{
$errorSchema->addError($errorSchemaLocal, (string) $key);
}
}
// Throws the error for the main form
if (count($errorSchema))
{
throw new sfValidatorErrorSchema($this, $errorSchema);
}
return $values;
}
}