Saving object in database not based on primary key

9 views
Skip to first unread message

in...@yuzi.nl

unread,
May 21, 2021, 6:39:33 AMMay 21
to Joomla! General Development
Hello,

I have an issue that I need to deal with but I am not sure how to achieve this.

I have a Table class which has a primary key 'id', but there is another field as well "user_id". This is a unique key, related to the user id in the com_users table.

But when I try to add a record to the database I get the following error: 

Duplicate entry '185' for key 'user_id'

This ofcourse is logical, because in this case it needs to run an update, instead of an insert. How do I achieve this, do I override the store() method in the Table class?

seraphim

unread,
May 21, 2021, 7:06:20 AMMay 21
to joomla-de...@googlegroups.com

Hope this will bring you further.

Op 21-05-2021 om 12:39 schreef in...@yuzi.nl:
--
You received this message because you are subscribed to the Google Groups "Joomla! General Development" group.
To unsubscribe from this group and stop receiving emails from it, send an email to joomla-dev-gene...@googlegroups.com.
To view this discussion on the web, visit https://groups.google.com/d/msgid/joomla-dev-general/c057b90d-8366-493a-914b-dd62b532e10fn%40googlegroups.com.


in...@yuzi.nl

unread,
May 21, 2021, 7:18:19 AMMay 21
to Joomla! General Development
This seems way too overcomplicated, and not utilizing the JTable class?

I found mabye another solution:

You should propagate JTable for this case ; ) if(JTable->load([$key => $value])) return true if record exists and false if record not exists then you can use ->store to insert / update record.

Op vrijdag 21 mei 2021 om 13:06:20 UTC+2 schreef seraphim:

in...@yuzi.nl

unread,
May 21, 2021, 7:46:27 AMMay 21
to Joomla! General Development
Found the solution. Instead of doing this in the Location table, I moved it into my model:

 //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;
    }

Op vrijdag 21 mei 2021 om 13:18:19 UTC+2 schreef in...@yuzi.nl:
Reply all
Reply to author
Forward
0 new messages