user2314339
user2314339

Reputation: 393

Delete record from multiple tables when using a View CakePHP 2.8.x

I am using CakePHP 2.8.x and i'm looking for a way to delete records from 2 tables with 1 delete action.

I created a View from 3 tables: visitors, guests and registrations. These tables are connected through visitor_id.

In the Visitor Model i added the View in $useTable. Now when i press delete on, for example, visitor 1, i want to delete the records from visitor 1's guests and registrations tables and keep the visitor information in the visitor's table

I did found $this->Visitor->delete($id), but what parameters do i need to add to this function, so i can delete just the records from the guests and registrations tables?

If i need to give more information, i'm happy to help! Thx in advance

Update: The tables are associated. These are the models:

Visitor:

public $hasMany = array(
    'Guest' => array(
        'className' => 'Guest',
        'foreignKey' => 'visitor_id',
        'dependent' => false,
        'exclusive' => false,
    ),
    'Registration' => array(
        'className' => Registration',
        'foreignKey' => 'visitor_id',
        'dependent' => false,
        'exclusive' => false,
    ),

);  

public $belongsTo = array(

);  

Registration:

public $belongsTo = array(
    'Visitor' => array(
        'className' => 'Visitor',
        'foreignKey' => 'visitor_id',
    ),

);  

Guest:

public $belongsTo = array(
    'Visitor' => array(
        'className' => 'Visitor',
        'foreignKey' => 'visitor_id',
    ),

Upvotes: 0

Views: 387

Answers (2)

Riajul Islam
Riajul Islam

Reputation: 1483

you can try it,its worked for me

public function your_action($id=null){
    $this->MainMdel->ConnectedModel1->deleteAll(array('ConnectedModel_id' => $id));
    $this->MainMdel->ConnectedModel2->deleteAll(array('ConnectedModel_id' => $id));
    }

Upvotes: 0

arilia
arilia

Reputation: 9398

there's the deleteAll() function in cake 2 (see the cookbook)

you have to pass to the function an array of conditions. In your case you want to delete all the Guests that have visitor_id = $id (the same for Registration).

$this->Visitor->Guest->deleteAll(array('visitor_id' => $id));

$this->Visitor->Registration->deleteAll(array('visitor_id' => $id));

this will delete all the Guests and the Registrations of the Visitor without touching the Visitor itself

Upvotes: 3

Related Questions