tags:

views:

107

answers:

4

In CakePHP, Is it possible to insert into another table with the other model not related to it. For eg, i m having a model Post .is it possible for me to use $this->Post->query('insert into tablename(col1) values (' . "$formname" . ')');

Suggest me the answer......

+1  A: 

You could use the 'uses' var to specify the models you want to use in your controller:

var $uses = array('Recipe', 'User');

This would tell the controller (in this case RecipesController) to use the User model as well as it's default Model (Recipe). Now you can address $this->User as if you were in the UsersController.

Hope I understood your question correctly.

Tom

Tom Wright
ya now i m getting the answer
Aruna
+1  A: 

Create a model for the other table then you can write to the table at any time using this :

<?php 
  App::import('Model', 'MyModel');
  $this->MyModel = new MyModel;
  $this->MyModel->save($MyData);
?>
Ronny Vindenes
A: 

Yes, with query() you can execute any SQL statements, and so it is also possible to use this method to insert data, like you did in your example.

However, usually one of the other approaches mentioned is used.

dhofstet
A: 

Use Model::query() only when absolutely necessary and there is no other way (i.e. in extreme cases). Cake gives you a lot of tools to avoid doing that.

The most simple solution would be to use the following:

$otherModel = ClassRegistry::init('OtherModel');
$otherModel->save(<your usual stuff here>);

ClassRegistry::init() returns an instance of your model (it is a bad idea to do that yourself), and is an easy way to access any model in your app.

If you use the "var $uses" method, OtherModel will be loaded always for that controller, which might not be what you want (it brings a lot of unnecessary overhead).

dr Hannibal Lecter