I'm trying to save some data into a model.
This is the table:
CREATE TABLE "user_dashboard_configs"(
"user_dashboard_config_id" serial NOT NULL,
"user_id" integer,
"module_id" integer,
"graphic_id" integer,
"dc_show" boolean,
"graphic_type" varchar(20),
CONSTRAINT "user_dashboard_configs_pkey" PRIMARY
KEY("user_dashboard_config_id"),
)
This is the Model:
class UserDashboardConfig extends AppModel {
public $name = 'UserDashboardConfig';
//public $useTable = 'user_dashboard_configs';
public $primaryKey = 'user_dashboard_config_id';
var $belongsTo = array(
'Module' => array(
'className' => 'Module',
'foreignKey' => 'module_id',
),
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
)
);
}
And the add() function
...
$this->UserDashboardConfig->create();
$save['UserDashboardConfig']['user_id'] = intval($request['user_id']);
...
$save['UserDashboardConfig']['graphic_type'] = $value;
$this->UserDashboardConfig->save($save);
...
// also tried with
// $this->UserDashboardConfig->set(array(
// 'user_id' => intval($request['user_id'],
// ...
// )));
This debug:
debug($this->UserDashboardConfig->getDataSource()->getLog(false, false));
Returns:
(int) 8 => array(
'query' => 'BEGIN',
'params' => array(),
'affected' => (int) 0,
'numRows' => (int) 0,
'took' => (float) 1
),
(int) 9 => array(
'query' => 'INSERT INTO "public"."user_dashboard_configs" ("user_id", "module_id", "graphic_id", "dc_show", "graphic_type") VALUES (4, 57, 6, 'FALSE', 'bar_line')',
'params' => array(),
'affected' => (int) 1,
'numRows' => (int) 1,
'took' => (float) 0
),
(int) 10 => array(
'query' => 'COMMIT',
'params' => array(),
'affected' => (int) 1,
'numRows' => (int) 1,
'took' => (float) 0
)
The INSERT instruction when pasted into pgAdmin stores the data correctly, but CakePHP does not store it, despite not throwing errors.
Just noticed this: the sequence on the DB is increasing, so there is kind of an insert, but the data is not shown on the table.
Could this be a postgresql / phAdmin problem?
Can someone help on how to solve this?
Already tried:
https://stackoverflow.com/a/10198674/5525602
https://stackoverflow.com/a/20502819/5525602
https://stackoverflow.com/a/20824941/5525602
http://headynation.com/cakephp-model-save-function-returning-false-without-an-error-or-sql-statements/
Related
I have a simple HABTM with a lessons/Students table. i simply create a new lesson with an existing student via a while loop , so I should get 2 new rows. I am testing this function. What I get is 4 new rows in the lesson table instead of 2. I have no idea why the extra 2 rows are created as they are a duplicates of the 2 new rows which are outputted in debug. Everything is correctly saved like the entries in join lesson/student table and all the FK exist.
Just to add confusion, sometimes the same code produces the desired 2 rows . This is unstable so I am doing something wrong. I followed the array setup for habtm as in the manual for saves.
http://book.cakephp.org/2.0/en/models/saving-your-data.html
private function book_lessons($lesson=null) {
// debug( $lesson);
$i=0;
while ($i<2)
{
$date=date('Y-m-d');
$data[$i]=array();
$this->Lesson->create();
$data[$i]['Lesson']['lesson_date']= $date;
$data[$i]['Lesson']['start_time']= $lesson['Lesson']['start_time'];
$data[$i]['Lesson']['end_time']=$lesson['Lesson']['end_time'];
$data[$i]['Lesson']['schedule_rec']= 1;
$data[$i]['Lesson']['subject_id']= $lesson['Lesson']['subject_id'];
$data[$i]['Lesson']['tutoring_type_id']= 1;
$data[$i]['Lesson']['tutor_id']= $lesson['Lesson']['tutor_id'];
$data[$i]['Lesson']['subject_id']= $lesson['Lesson']['subject_id'];
$data[$i]['Lesson']['term_id']= $lesson['Lesson']['term_id'];
$data[$i]['Student']['id']=$lesson['Student']['id'];
$i=$i+1;
}
$this->Lesson->saveAll($data);
public $hasAndBelongsToMany = array(
'Student' => array(
'className' => 'Student',
'joinTable' => 'lessons_students',
'foreignKey' => 'lesson_id',
'associationForeignKey' => 'student_id',
'unique' => 'keepExisting',
)
);
array(
(int) 0 => array(
'Lesson' => array(
'lesson_date' => '2015-06-11',
'start_time' => '16:00:00',
'end_time' => '17:00:00',
'schedule_rec' => (int) 1,
'subject_id' => '16',
'tutoring_type_id' => (int) 1,
'tutor_id' => '12',
'term_id' => '10'
),
'Student' => array(
'id' => '206'
)
),
(int) 1 => array(
'Lesson' => array(
'lesson_date' => '2015-06-11',
'start_time' => '16:00:00',
'end_time' => '17:00:00',
'schedule_rec' => (int) 1,
'subject_id' => '16',
'tutoring_type_id' => (int) 1,
'tutor_id' => '12',
'term_id' => '10'
),
'Student' => array(
'id' => '206'
)
)
)
Move the $this->Lesson->create(); out of the loop. Cake will still save multiple records when you have only in create() method.
Hello I m creating simple blog site here view blog at landing page but if user choose any category the blog under this category only listed . My problem is when user select category from right sidebar it return all table records.
When i print the query it return :
array(
'log' => array(
(int) 0 => array(
'query' => 'SELECT `Category`.`category_id`, `Category`.`name` FROM `cakeBlog`.`categories` AS `Category` WHERE 1 = 1',
'params' => array(),
'affected' => (int) 13,
'numRows' => (int) 13,
'took' => (float) 0
),
(int) 1 => array(
'query' => 'SELECT `Post`.`id`, `Post`.`category_id`, `Post`.`title`, `Post`.`body`, `Post`.`created`, `Post`.`modified`, `Post`.`user_id` FROM `cakeBlog`.`posts` AS `Post` WHERE 1 = 1 LIMIT 20',
'params' => array(),
'affected' => (int) 13,
'numRows' => (int) 13,
'took' => (float) 0
)
),
'count' => (int) 2,
'time' => (float) 0
)
Here is my controller file
PostsController.php
In index function I will check whether category id exist or not?
Please help me...
Thanks
Use the following block where you want to fetch categories
if(is_null($categoryId)) {
$this->Paginator->setting = array(
'limit' =>'10',
'order' => array('Post.id' =>'Desc')
/*'conditions' => array(
'Post.user_id' => AuthComponent::user(id)
)*/
);
$arrPosts = $this->Paginator->paginate('Post');
$this->set('posts', $arrPosts);
} else {
$condition = array('Post.category_id' => $categoryId,'limit' =>'10');
$da = $this->Paginator->setting = array(
'conditions' => $condition
/*'conditions' => array(
'Post.user_id' => AuthComponent::user(id)
)*/
);
$arrPosts = $this->Paginator->paginate('Post');
$log = $this->Post->getDataSource()->getLog(false, false); debug($log);
$this->set('posts', $arrPosts);
}
I use softdelete Behaviour of Utils Plugin for CakePHP 2.x
I have following 4 tables
customers
customer_addresses
customer_contacts
customer_reports
And consider following its relationship with each other,
1. for customers
Customer hasMany CustomerAddress
Customer hasMany CustomerContact
Customer hasMany CustomerReport
public $hasMany = array(
'CustomerAddress' => array(
'className' => 'CustomerAddress',
'foreignKey' => 'customer_id',
'dependent' => true,
),
'CustomerContact' => array(
'className' => 'CustomerContact',
'foreignKey' => 'customer_id',
'dependent' => true,
),
'CustomerReport' => array(
'className' => 'CustomerReport',
'foreignKey' => 'customer_id',
'dependent' => true,
)
);
2. for customer_addresses
CustomerAddress belongsTo Customer
CustomerAddress belongsTo State
CustomerAddress hasOne CustomerContact
CustomerAddress hasOne CustomerReport
public $belongsTo = array(
'Customer' => array(
'className' => 'Customer',
'foreignKey' => 'customer_id',
'dependent' => false,
),
'State' => array(
'className' => 'State',
'foreignKey' => 'state_id',
)
);
public $hasOne = array(
'CustomerContact' => array(
'className' => 'CustomerContact',
'foreignKey' => 'customer_address_id',
'dependent' => true,
),
'CustomerReport' => array(
'className' => 'CustomerReport',
'foreignKey' => 'customer_address_id',
'dependent' => true,
)
);
3. for customer_contacts
CustomerContact belongsTo Customer
CustomerContact belongsTo CustomerAddress
public $belongsTo = array(
'Customer' => array(
'className' => 'Customer',
'foreignKey' => 'customer_id',
'dependent' => false,
),
'CustomerAddress' => array(
'className' => 'CustomerAddress',
'foreignKey' => 'customer_address_id',
'dependent' => true,
)
);
4. for customer_reports
CustomerReport belongsTo Customer
CustomerReport belongsTo CustomerAddress
public $belongsTo = array(
'Customer' => array(
'className' => 'Customer',
'foreignKey' => 'customer_id',
'dependent' => false,
),
'CustomerAddress' => array(
'className' => 'CustomerAddress',
'foreignKey' => 'customer_address_id',
'dependent' => true,
)
);
I have put below code in bootstrap.
CakePlugin::load('Utils');
I have also added below actAs in all above model
public $actsAs = array('Containable','Utils.SoftDelete');
I have already put below code in my appModel.
// for softdelete, checking exist id
public function exists($id = null) {
if ($this->Behaviors->attached('SoftDelete')) {
return $this->existsAndNotDeleted($id);
} else {
return parent::exists($id);
}
}
// for softdelete, overrite delete method
public function delete($id = null, $cascade = true) {
$result = parent::delete($id, $cascade);
if ($result === false && $this->Behaviors->enabled('SoftDelete')) {
return $this->field('deleted', array('deleted' => 1));
}
return $result;
}
When I try to cascade delete with out soft delete ( means simple cascade delete ) , it works fine.
But My problem is that.
When I use softdelete behaviour of Utils plugin , Cascade delete does not work.
I have tried to delete record using below code
if ($this->CustomerAddress->delete()) {
$this->Session->setFlash(__('CustomerAddress deleted'));
$this->redirect($this->referer());
}
SQL log
array(
'log' => array(
(int) 0 => array(
'query' => 'SELECT COUNT(*) AS `count` FROM `lewie`.`customer_addresses` AS `CustomerAddress` LEFT JOIN `lewie`.`customers` AS `Customer` ON (`CustomerAddress`.`customer_id` = `Customer`.`id`) LEFT JOIN `lewie`.`states` AS `State` ON (`CustomerAddress`.`state_id` = `State`.`id`) LEFT JOIN `lewie`.`customer_contacts` AS `CustomerContact` ON (`CustomerContact`.`customer_address_id` = `CustomerAddress`.`id`) LEFT JOIN `lewie`.`customer_reports` AS `CustomerReport` ON (`CustomerReport`.`customer_address_id` = `CustomerAddress`.`id`) WHERE `CustomerAddress`.`id` = 43 AND `CustomerAddress`.`deleted` = '0'',
'params' => array(),
'affected' => (int) 1,
'numRows' => (int) 1,
'took' => (float) 0
),
(int) 1 => array(
'query' => 'SELECT COUNT(*) AS `count` FROM `lewie`.`customer_addresses` AS `CustomerAddress` LEFT JOIN `lewie`.`customers` AS `Customer` ON (`CustomerAddress`.`customer_id` = `Customer`.`id`) LEFT JOIN `lewie`.`states` AS `State` ON (`CustomerAddress`.`state_id` = `State`.`id`) LEFT JOIN `lewie`.`customer_contacts` AS `CustomerContact` ON (`CustomerContact`.`customer_address_id` = `CustomerAddress`.`id` AND `CustomerContact`.`deleted` = '0') LEFT JOIN `lewie`.`customer_reports` AS `CustomerReport` ON (`CustomerReport`.`customer_address_id` = `CustomerAddress`.`id` AND `CustomerReport`.`deleted` = '0') WHERE `CustomerAddress`.`id` = 43 AND `CustomerAddress`.`deleted` = '0'',
'params' => array(),
'affected' => (int) 1,
'numRows' => (int) 1,
'took' => (float) 1
),
(int) 2 => array(
'query' => 'SELECT COUNT(*) AS `count` FROM `lewie`.`customer_addresses` AS `CustomerAddress` LEFT JOIN `lewie`.`customers` AS `Customer` ON (`CustomerAddress`.`customer_id` = `Customer`.`id`) LEFT JOIN `lewie`.`states` AS `State` ON (`CustomerAddress`.`state_id` = `State`.`id`) LEFT JOIN `lewie`.`customer_contacts` AS `CustomerContact` ON (`CustomerContact`.`customer_address_id` = `CustomerAddress`.`id` AND `CustomerContact`.`deleted` = '0') LEFT JOIN `lewie`.`customer_reports` AS `CustomerReport` ON (`CustomerReport`.`customer_address_id` = `CustomerAddress`.`id` AND `CustomerReport`.`deleted` = '0') WHERE `CustomerAddress`.`id` = 43 AND `CustomerAddress`.`deleted` = '0'',
'params' => array(),
'affected' => (int) 1,
'numRows' => (int) 1,
'took' => (float) 0
),
(int) 3 => array(
'query' => 'UPDATE `lewie`.`customer_addresses` SET `deleted` = '1', `deleted_date` = '2014-05-27 10:46:43', `modified` = '2014-05-27 10:46:43' WHERE `lewie`.`customer_addresses`.`id` = '43'',
'params' => array(),
'affected' => (int) 1,
'numRows' => (int) 1,
'took' => (float) 0
),
(int) 4 => array(
'query' => 'SELECT `CustomerAddress`.`deleted` FROM `lewie`.`customer_addresses` AS `CustomerAddress` WHERE `deleted` = '1' LIMIT 1',
'params' => array(),
'affected' => (int) 1,
'numRows' => (int) 1,
'took' => (float) 0
)
),
'count' => (int) 5,
'time' => (float) 1)
How can I resolve this problem?
I have a problem with habtm with cakephp and i dont know how to solve yet. I've got three tables: setores, veiculos e setores_veiculos.
Setor model:
public $hasAndBelongsToMany = array(
'Veiculo' => array(
'className' => 'Veiculo',
'joinTable' => 'setores_veiculos',
'foreignKey' => 'setor_id',
'associationForeignKey' => 'veiculo_id',
'unique' => 'keepExisting'
)
);
Veiculo model:
public $hasAndBelongsToMany = array(
'Setor' => array(
'className' => 'Setor',
'joinTable' => 'setores_veiculos',
'foreignKey' => 'veiculo_id',
'associationForeignKey' => 'setor_id',
'unique' => 'keepExisting'
)
);
In my setores controller i have:
$options = array('conditions' => array('Setor.' . $this->Setor->primaryKey => $id));
$setores = $this->Setor->find('first', $options);
then in my debug:
array(
'Setor' => array(
'id' => (int) 5,
'nome' => '2º Batalhão',
'secretaria_id' => (int) 6,
'sigla' => '2º BPM',
'status_id' => (int) 1
),
'Veiculo' => array()
)
I can not understand why the Veiculo (vehicle) are not being listed. The insertion is working perfectly.
I expected:
'Veiculo' => array(
0 => array(
'id' => 1,
'name' => 'Corolla'
),
1 => array(
'id' => 2,
'name' => 'Hillux'
)
);
In my veiculos controller the setores are being listed. Any suggestion?
Thank you in advance and sorry about my english.
Looks fine to me. Try changing
'unique' => 'keepExisting'
to
'unique' => true
At present, I go by the simple rules as explained in the documentation that if I am using a simple link table, i.e. not storing any data in it, I use HABTM and unique set to true, otherwise I use hasMany through (The Join Model) and unique set to keepExisting so as not to lose extra stored data.
Post a data dump of setores_veiculos.
Problem:
I have two models: Dealer, Testdrive (Testdrive belongs to Dealer through dealer_id). I want to show real time statistics about the dealers: total (Testdrive.active = 1), processed (Testdrive.active = 1 && Testdrive.processed = 1) ...
I have approx 100 dealers and 10000 testdrives. The count based sql takes about 10 sec (inefficient). Now i have a cronjob that runs every hour but I don't have real time stats.
I tried something like this:
var $belongsTo = array(
'Dealer' => array(
'className' => 'Dealer',
'foreignKey' => 'dealer_id',
'counterCache' => 'active',
'counterScope' => array('Testdrive.active' => 1),
'conditions' => '',
'fields' => '',
'order' => ''
),
'Dealer' => array(
'className' => 'Dealer',
'foreignKey' => 'dealer_id',
'counterCache' => 'processed',
'counterScope' => array('Testdrive.active' => 1, 'Testdrive.processed' => 1),
'conditions' => '',
'fields' => '',
'order' => ''
)
);
... but i overwritten the belongsTo => 'Dealear' value.
Can I have an array of counterCache with an array of counterScope?
var $belongsTo = array(
'Dealer' => array(
'className' => 'Dealer',
'foreignKey' => 'dealer_id',
'counterCache' => array('active', 'processed'),
'counterScope' => array('active' => array('Testdrive.active' => 1), 'processed' => array('Testdrive.active' => 1, 'Testdrive.processed' => 1)),
'conditions' => '',
'fields' => '',
'order' => ''
),
);
There's (now) an example of this in the documentation. Applied to the example in the question that would be:
class TestDrive extends AppModel {
public $belongsTo = array(
'Dealer' => array(
'counterCache' => array(
'active' => array(
'TestDrive.active' => 1
),
'processed' => array(
'TestDrive.active' => 1,
'TestDrive.processed' => 1
)
)
)
);
}
Note there's no need to define keys with default values (className, foreignKey etc.).