krissanawat
krissanawat

Reputation: 626

How to use more than one model in a CakePHP controller

I have created a registration form and I send data to the controller.

I want to insert this data to 3 different tables (models).

How can this be achieved?

Upvotes: 4

Views: 13596

Answers (3)

Chris Pierce
Chris Pierce

Reputation: 736

This is actually best to loade the model on the fly as that way you don't load it for all methods that you may not need.

$this->loadModel('Model1');

Way more efficient.

I'd also recommend making sure these tables aren't linked. If they are then its best to chain them through via:

$this->Model1->Model2->find();

This is the beginning of teaching you to be more efficient with tables via Containable and Relationships (HasMany, BelongsTo, HABTM)

Upvotes: 0

Oerd
Oerd

Reputation: 2303

What you mean (in CakePHP terms) is that you want to use more models than the default one. the default model is the one named like your controller.

To achieve what you want you just declare a variable $uses in your controller. It's done like this:

<?php
class ExampleController extends AppController {
    var $name = 'Example';

    // $uses is where you specify which models this controller uses
    var $uses = array('Model1', 'Model2', 'ModelN');

    // ... here go your controller actions (methods)

}
?>   

This will allow your controller to make use of Model1, Model2 and ModelN. Rename those and add more according to your needs.

If you do not wish to use models in your controller, you can assign $uses to an empty array, i.e.:

var $uses = array();

Take a look at the corresponding CakePHP book chapters according to the version you're using:

Upvotes: 19

vindia
vindia

Reputation: 1678

As long as your forms are formatted according to the CakePHP conventions and the relations between the Models will be set up correctly, this will be done automatically when you invoke $this->Model->save($this->data).

Upvotes: 1

Related Questions