useranon
useranon

Reputation: 29514

Can CakePHP insert data into an model using an unrelated `$this->Model->query()` method?

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

Suggest me the answer......

Upvotes: 0

Views: 1332

Answers (4)

dr Hannibal Lecter
dr Hannibal Lecter

Reputation: 6721

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).

Upvotes: 0

dhofstet
dhofstet

Reputation: 9964

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.

Upvotes: 0

Ronny Vindenes
Ronny Vindenes

Reputation: 2361

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);
?>

Upvotes: 1

Tom Wright
Tom Wright

Reputation: 11489

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

Upvotes: 2

Related Questions