ziyaaf gaffoor Sun Oct 30 02:29:51 -0400 2011

Subject: Delete - Table relations

Hi All,

Im new to this amazing library and I need help with this:

'User' table and 'Payments' table has 1-many relationship. I need to delete all user related payment when a user is deleted. I know how to print all payments related to a particular user . But i do not know how to delete all payments related to that user.

Can someone please help me with that.


kemal birinci Thu Nov 03 21:10:51 -0400 2011

I thought it delete all related lines from other tables:( I looked my tables and it did not delete.

So I have same problem.

Yoan B Fri Nov 04 11:53:07 -0400 2011

It's related to the database you're using, mostly. afaik PostgreSQL supports cascading deletion but not MySQL, SQLite, …

You should use delete_all to remove all the related lines and then delete your stuff.


Try to set up InnoDB foreign key, it'll keep your DB sane.

ziyaaf gaffoor Fri Nov 04 21:42:58 -0400 2011

Thanks for the reply.

Can u please explain the purpose of defining relationships in phpactiverecord, if we have to manually delete records related to a particular row.

Yoan B Sat Nov 05 04:48:41 -0400 2011

PHP-AR is an abstraction level atop your database and it doesn't know all about it. The relationship you define are useful for getting stuff (what you do most of the time).

1 $myuser->payments;
3 $myuser->delete(); // will only delete the $myuser, not any payments.

You can override the delete method in your user. (This code hasn't been tested and I might be a little bit rusty)

1 class User extends … {
23     function delete() {
4         Payments::delete_all(array('conditions' => array('user_id' => $this->id)));
5         return parent::delete();
6     }
7 }
karl metum Thu Jul 11 04:58:38 -0400 2013

One should instead use before_destroy().

Here's an example:

class User extends … {
    public function before_destroy()
        $related_payment = Payments::find(array(
            'conditions' => array(
                'user_id' => $this->id)