Magento 1.9 Database – Delete Query with Foreign Key

databasemagento-1.9query

How to delete the table record in magento using the foreign key.
I have a two table.

question(table 1)
--------
question_id
question

answer(table 2)
------
answer_id
question_id
answer

When I delete the question that corresponding answer also need to delete. I did the the question(table 1) record delete using the below method.

 $model->load($id)
 $model->setId($model->getQuestionId())->delete()

There have any way to delete the answer(table 2) record in the above method

Best Answer

Try this:

$model->load($id);
$model->delete();

//delete answer
$answer_cllection = Mage::getModel('answer/model')->getCollection()->addFieldToFilter('question_id', $id);
foreach($answer_collection as $answer){
    $answer->delete();
}

Assumption

answer/model need to be replaced with your answer model name to call your answer model and $id is question id.

Related Topic