PHP

Deleting related entries (children) automatically with the cakePHP model

Posted on: June 19th, 2012 by taff 1 Comment

Deleting related items (i.e. all posts when a thread is deleted) with the cakephp model is a breeze. All you need to do is make that model dependent (not dependant, a typo that cost me 20 minutes). So in my posts model I would have:

var $belongsTo = array(
	'Thread' => array(
          'className' => 'Thread',
	  'foreignKey' => 'thread_id',
	  'dependent' => true)
	);

Calling $this->Thread->del($id) will now not only delete all threads, but also any related posts which have a corresponding thread_id. This expels the chance of redundant data filling up your database.

Retrieving related data is also easy with the cakephp model, a simple

$this->recursive = 1

will get related data from the database, including data in a HasAndBelongsToMany relationship. Easy as pie...err cake

One Response

  1. Jim

    December 16, 2012

    Great post, really enjoyed it!
    — Jim

    http://www.bigconceptdesigns.com

    Reply

Leave a Reply