model

 

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

Setting up multiple databases with cakePHP

Posted on: August 7th, 2009 by taff 1 Comment

 

Yet again I been pleasantly surprised at how easy cakePHP handles things. This time it's the use of multiple databases. The current setup of our system has data stored in 4 databases.

For our example we will presume our multiple databases are setup as such:

We have a users database (which contains everyone we have ever had contact with) and is used by our CRM software. We then have our database containing all the products that our application has stored.

Our first step would be to configure all our configurations in app/config/database.php. It could look something like this:

<?php
class DATABASE_CONFIG {
	var $default = array(
		'driver' => 'mysql',
		'persistent' => false,
		'host' => 'localhost',
		'login' => 'hopefully_not_root',
		'password' => 'hardtoguess',
		'database' => 'products',
	);
	
	var $users = array(
		'driver' => 'mysql',
		'persistent' => false,
		'host' => 'localhost',
		'login' => 'hopefully_not_root',
		'password' => 'hardtoguess',
		'database' => 'users',
	);
}
?>

I know it's hard to believe but cakePHP will use default if it's there. What an apt name! 😉

Our Products model will then look something like this:

class Product extends AppModel {

    var $name = 'Product';
    //The next line could be omitted...default is default 😉
    var $useDbConfig = 'default';
    
    //Validation etc.. could go here
    
} 

Our Users Model would look similar:

Our Products model will then look something like this:

class User extends AppModel {

    var $name = 'User';
    var $useDbConfig = 'users';
    
    //Validation etc.. could go here
    
} 

That's it.

$this->Product->find() will now query our products database, and $this->User->find() our users database.

Taff