i am having trouble with cakephp and writing an sql query, I have the sql code written out but am not sure on how to code it in cake.
`users` - id, name, address
`accounts` - id, companyname, abn
`accounts_users` - id, account_id, user_id
`templates` - id, name, description, account_id
`fields` - id, name, description, template_id
- users habtm accounts
- accounts habtm users
- accounts hasMany templates
- templates belongsTo accounts
- templates hasMany fields
- fields belongsTo templates
what I am trying to get my find statement in the fieldscontroller, to add the template_id field is to do is this
select t.id
from template.t, account_users.au, user.u
where t.account_id=au.account_id AND
au.user_id=users.id;
this is the code I have so far in my fields in controller:
function add() {
$this->Session->setFlash("Please create your required fields.");
$templates = $this->Template->find('list', array(
'fields' => array('id'),
'conditions' => array('id'=> $this->Auth->user('id'))));
$this->set('templates','$templates');
if($this->request->is('post')) {
$this->Field->create();
if ($this->Field->save($this->request->data)) {
if ($this->request->data['submit'] == "type_1") {
$this->Session->setFlash('The field has been saved');
$this->redirect(array(
'controller' => 'fields',
'action' => 'add'));
}
if ($this->request->data['submit'] == "type_2") {
$this->Session->setFlash('The template has been saved');
$this->redirect( array('controller' => 'templates','action' => 'index'));
}
} else {
$this->Session->setFlash('The field could not be saved. Please, try again.');
}
}
}
the sql statement it currently is printing out is
SELECT `Template`.`id` FROM `pra`.`templates` AS `Template` WHERE `id` = 14
id is referring to the users table id
The error is i am trying to get the template_id in the the add form. the find function isn’t getting the template_id’s, it is instead grabbing the user – id
I think there’s something wrong with your field names. Are they in line with the code/name conventions?
Please post the table layout of the models.
if template_id is the primary key for the table templates you should use:
in your templates model.
http://book.cakephp.org/2.0/en/models/model-attributes.html#primarykey
and offcourse your getting what your asking. The query should be more like:
But that is dificult to say without your exact table layout.