I'm trying to insert a row with the table->save()
method, but the method executes an UPDATE instead. There is no row available, so it needs to be inserted. Does anyone know how to get it inserted?
My code:
$tableLocation = $this->getTable("Location", 'Table', array());
if (!$tableLocation->save($data))
{
$this->setError($user->getError());
return false;
}
This runs the query UPDATE, but it needs to be INSERT if not available.
EDIT: Ok so I found the solution, partly. My construct method in my Table class:
parent::__construct('#__matches_location', 'user_id', $db);
Because I set the primary key to the user_id field it tried to update. So I changed it to this:
parent::__construct('#__matches_location', 'id', $db);
But now I get another issue:
Duplicate entry '185' for key 'user_id'
This is correct, there is a record for 185 in it already.
The correct way is to use the id as primary key, but then I need to change the Location table store (?) method to set everything right. Is that correct?
Ok so I tried the following:
public function bind($array, $ignore = '')
{
if($this->load(['user_id' => $array['user_id']])) {
$array['id'] = $this->id;
}
//echo $this->id;
return parent::bind($array, $ignore);
}
This gives me an memory error. Probably a memory leak somewhere. So I moved the code to the store fucntion:
public function store($updateNulls = false)
{
if($this->load(['user_id' => $this->user_id])) {
$this->id = $this->id;
}
return parent::store($updateNulls);
}
But this doesn't do anything, because well, I load the row, and thus the new values sent are being overwritten. Do I need to get these values first and then change them in the new loaded row?
It all seems so cumbersome, there must be an easier way right? I cannot imagine this is some sort of unique situation.
SOLUTION:
//Store data, check if records exist
if($tableLocation->load(['user_id' => $data['user_id']])) { $data['id'] = $tableLocation->id; }
if (!$tableLocation->save($data))
{
$this->setError($user->getError());
return false;
}
'Table'
orarray()
-- these are default parameters. This advice will not resolve your question, but it does mean that you can simplify your call to$this->getTable("Location")
. Your question is missing some vital details. What does$data
contain? You say that a row is being updated -- is only one row updated or multiple? How are the updated rows targeted? What is the rendered executed query?