Yii2 deactivate behavior TimestampBehavior when saving update_at - php

I am programming a ConsoleController command for edit some values in some Databases.
The problem is when I try to save the Model.
//console/controllers/ConsoleController.php
public function actionChangeCourseTitle()
{
$model = Course::find->where([ 'id' => $id])->all();
$model->title = "new title";
$model->detachBehaviors(); //for deactivate the TimestampBehavior
$model->save();
}
I want to deactivate the automatic save of the timestamp in the field "update_at", with the $model->detachBehaviors() as explained in the yii2 documentation (https://www.yiiframework.com/doc/guide/2.0/en/concept-behaviors#detaching-behaviors). But does not works.
Do you have any idea why does not works? am I defining wrong the detachBehaviors()?
Best Regards,
Paul
Update: it was edited in the SQL Definition of the table.
CREATE TABLE course (
...
updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
...
)
I solve the problem with ALTER COLUMN as SQL Query...
ALTER TABLE course
MODIFY COLUMN updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP;
and I could edit the fields without updating automaticly the field "update_at".

Update: it was edited in the SQL Definition of the table.
CREATE TABLE course ( ...
updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
... )
I solve the problem with ALTER COLUMN as SQL Query...
ALTER TABLE course MODIFY COLUMN updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP;
and I could edit the fields without updating automaticly the field "update_at".

Related

Unable to alter database table

I want to add a new column in table so i am running following mysql command.
alter table student add doe datetime not null default curdate();
But it says I have error in mysql statement near curdate();
Modify your query as below.
ALTER TABLE `student` ADD `doe` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ;
it should solve your answer.
Thanks
Amit
The error occurs because you can't use function as default value.
It is available from MySQL version 5.6.5. Check this:
http://optimize-this.blogspot.co.uk/2012/04/datetime-default-now-finally-available.html
Previous versions can deal with timestamp type:
ALTER TABLE student ADD doe TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;
You should use this:
alter table student add doe datetime not null default now();

Updating date by CURRENT_TIMESTAMP .. Why all Zeros?

I am trying to update date whenever any updates occur on the record, the field type is datetime and I set the default value to CURRENT_TIMESTAMP. when update sql is excuted the result is all zeros!
0000-00-00 00:00:00
$sql = 'INSERT INTO product_shop_offers (id,product_id,shop_id,price,currency_id,added_by,last_update)'
. ' VALUES (?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE id=?,shop_id=?,price=?,currency_id=?,added_by=?,last_update=?';
$this->db->query($sql, array(
$storeInfoArray['recordId'],
$productId,
$storeInfoArray['storeNameNo'],
$storeInfoArray['price'],
$storeInfoArray['currency'],
$addedBy,
'CURRENT_TIMESTAMP()',
$storeInfoArray['recordId'],
$storeInfoArray['storeNameNo'],
$storeInfoArray['price'],
$storeInfoArray['currency'],
$addedBy,
'CURRENT_TIMESTAMP()'
))
Note: I checked Similar problem question but I didn't understand the problem!!can somebody help please.
Is it because you are binding in the string 'CURRENT_TIMESTAMP()'.. I'm not sure you can do that and it is being converted to zeros.
If you have the default set in the database, why bother binding it in at all? Just remove the field from the statement.. oh and you'll need to add the attribute ON UPDATE CURRENT_TIMESTAMP to the column:
ALTER TABLE product_shop_offers
MODIFY COLUMN last_update DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
If you need it otherwise, you may have to write it into the query directly.
I think it should be helpful for you
MySQL CURRENT_TIMESTAMP field updates on every update
Change CURRENT_TIMESTAMP() to NOW()
Another possible way is to set the field type from datetime to timestamp

Unable To Save Data In MySQL From A Custom Magento Module

I am making a custom module for Magento 1.7.0. I am facing a problem while trying to insert data into MySQL. I fetch the user information from the session as follows:
$customer = Mage::getSingleton('customer/session')->getCustomer();
$user_id = $customer->getId();
$user_id now carries ID of the current user logged into my Magento system.
Basically the problem is that when I try to save this above ID in my custom table, the value that is saved in my table is always 0.
Previously I faced this problem while trying to save another integer value, which I solved by changing the datatype of my MySQL table column from int(10) to tinyint(4), but in this case I cannot do so for the user ID.
$model= Mage::getModel('voter/competetion')
->setDesignid($designId)
->setUserId($user_id)
->setVote($vote)
->setStartdate($startDate)
->save();
The MySQL column name are as follows along with the install sql script: id, designid, user_id, vote, startdate, enddate
$installer = $this;
$installer->startSetup();
$prefix = Mage::getConfig()->getTablePrefix();
$installer->run("
CREATE TABLE IF NOT EXISTS ".$prefix."vote_competetion (
id int(10) NOT NULL AUTO_INCREMENT,
designid int(10) NOT NULL,
user_id int(10) NOT NULL,
vote tinyint(1) NOT NULL,
startdate datetime NOT NULL,
enddate datetime NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (designid) REFERENCES ".$prefix."vote_design(id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
");
Mage::getModel('core/url_rewrite')->setId(null);
$installer->endSetup();
Is there something wrong with my setter method name. All other values are being saved correctly. I am really not sure what to do about this. Please help.
I appreciate all the help.
Thanks!
If you didn't have user_id in the table from the start, you should clear the cache since Magento keeps it's structure cached and will not set any new columns data.
You have an error in naming of user id field. In table it is named as userid, so in your code you should call it like this:
$model= Mage::getModel('voter/competetion')
->setDesignid($designId)
->setUserid($user_id) // notice lowercase "i" here
->setVote($vote)
->setStartdate($startDate)
->save();
Or you can rename field in table from userid to user_id.

'created at' and 'updated at' fields

This seems like a really simple one but I'm struggling to figure it out. I want a column in my database that lists when a record was first created and another column that says when it was updated. It's my understanding I should be able to do all this just using MySQL. All help is appreciated :)
This stinks still no answer, reasons I'm already starting to miss Ruby on Rails...
You will probably need to use a combination of the Datetime datatype and the Timestamp data type. I would set my created column as a DateTime with a DEFAULT NOW(), and my updated column as a Timestamp with DEFAULT CURRENT_TIMESTAMP and an ON UPDATE CURRENT_TIMESTAMP attribute.
Here are the docs for the Timestamp dt:
http://dev.mysql.com/doc/refman/5.0/en/timestamp.html
In a CREATE TABLE statement, the first TIMESTAMP column can be declared in any of the following ways:
With both DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP clauses, the column has the current timestamp for its default value, and is automatically updated.
With neither DEFAULT nor ON UPDATE clauses, it is the same as DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP.
With a DEFAULT CURRENT_TIMESTAMP clause and no ON UPDATE clause, the column has the current timestamp for its default value but is not automatically updated.
With no DEFAULT clause and with an ON UPDATE CURRENT_TIMESTAMP clause, the column has a default of 0 and is automatically updated.
With a constant DEFAULT value, the column has the given default and is not automatically initialized to the current timestamp. If the column also has an ON UPDATE CURRENT_TIMESTAMP clause, it is automatically updated; otherwise, it has a constant default and is not automatically updated.
To fulfill your question and for others viewing this question, here is the answer. Note this was written for MySQL 5.x.
DROP TABLE IF EXISTS `test1`;
CREATE TABLE `test1` (
`id` INT NULL AUTO_INCREMENT ,
`name` varchar(50) NOT NULL ,
`created` DATETIME ,
`updated` DATETIME ,
PRIMARY KEY (`id`),
INDEX (`name`)
);
DELIMITER $$
DROP TRIGGER IF EXISTS `test1_created`$$
CREATE TRIGGER `test1_created` BEFORE INSERT ON `test1`
FOR EACH ROW BEGIN
SET NEW.`created` = UTC_TIMESTAMP();
SET NEW.`updated` = UTC_TIMESTAMP();
END;
$$
DROP TRIGGER IF EXISTS `test1_updated`$$
CREATE TRIGGER `test1_updated` BEFORE UPDATE ON `test1`
FOR EACH ROW BEGIN
SET NEW.`updated` = UTC_TIMESTAMP();
END;
$$
DELIMITER ;
Note
You could use TIMESTAMP for the updated column which would have automatically updated the value thus not requiring the BEFORE UPDATE trigger, however TIMESTAMP has a range from 1970 to 2038 which is fast approaching and I like to think my applications will live forever :). Although TIMESTAMP is only 4bytes while DATETIME is 8bytes.
TIMESTAMP range '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC
DATETIME range '1000-01-01 00:00:00' to '9999-12-31 23:59:59'
From the MySQL 5.0 Certification Guide:
CREATE TABLE ts_test5 (
created TIMESTAMP DEFAULT 0,
updated TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
data CHAR(30)
);
To control the initialization and update behaviour of a TIMESTAMP column, you add either or both of the DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP attributes to the column defintion when creating the table with CREATE TABLE...
and
...if you do not specify either of the DEFAULT CURRENT_TIMESTAMP or ON UPDATE CURRENT_TIMESTAMP attributes when creating a table, MySQL automatically assigns BOTH to the first TIMESTAMP column
Also
you cannot use DEFAULT CURRENT_TIMESTAMP with one column and ON UPDATE CURRENT_TIMESTAMP with another
If you can't use the timestamp fields with default attributes that Paul W has suggested, you can use AFTER INSERT and AFTER UPDATE triggers to populate the fields.
You will need two fields "Created" and
"Updated" with type datetime. When a
new entry is inserted then insert
"Created" with current time stamp.
When a update is happening insert
"Updated" with the current time stamp,
and let the "Created" field remain as
it is.
For current time stamp you can use
NOW() in your mysql query.

NOW() not updating datetime?

i have a table that looks like this:
Field: msg_sent_datetime
Type: datetime
yet when i use NOW() in a php mysql insert query it is staying as all zeros?
any idea why?
If you're using it only at the time of INSERT, you could make the field a TIMESTAMP and set a default of CURRENT_TIMESTAMP.
Without knowing more about the code it's difficult to suggest much else.
Example with CURRENT_TIMESTAMP
CREATE TABLE example (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
msg TEXT,
msg_sent_datetime TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Also, if you want it to always update when there's a change to the row, you can add the ON UPDATE CURRENT_TIMESTAMP property to the table definition:
CREATE TABLE example (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
msg TEXT,
msg_sent_datetime TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
Of course, all of this is totally dependent on switching to TIMESTAMP which you may not want
I dont knw exactly why, but mysql has 2 datetime functions: now() and sysdate(). Perhaps you can substitute now() with sysdate() to help you troubleshoot.
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_sysdate

Categories