Prevent Updating createdAt field each time flush entity - symfony-2.8

I'm using symfony 2 doctrine orm to update record. But each time updating record, TIMESTAMP field called createdAt value is changing ( set current date time ). How to prevent this behavior? see my code,
public function newsDetailsAction(Request $request)
{
....
$post = $this->getDoctrine()->getRepository('AdminBundle:BlogPostEntity')->findOneBy(array('postId' => $postid ));
$views = $post->getPostViews();
$post->setPostViews($views + 1);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($post);
$entityManager->flush();
...
}

My Bad. I was using timestamp for type. That's the issue.

Related

Transaction in cakephp- 3.0

In my cakephp3.0 application registration page the registration data is inserting into two tables. I am using query builder for doing this. After the successful insertion of data into the first table(Projects table) projectId(primary key of Projects table which is auto incremented value) will return and which is used to insert into second table that is ProjectCustomers table, in projectCustomers table projectId is used as forign key. My controller look like this
public function initialize() {
parent::initialize();
$this->Project = new ProjectsTable();
$this->ProjectCustomer = new ProjectCustomersTable();
}
public function add() {
if ($this->request->is('post')) {
$project_id = $this->Project->putProject($formData['survey_id'], $formData['title'], $formData['operator'], $this->Auth->user('id'));
$this->ProjectCustomer->putProjectCustomer($project_id, $formData['air_id'], $formData['email'], $formData['name'], $formData['company_name'], $formData['department_name'], SYS_ADMIN, PROJECT_CUSTOMER_STATUS_ACTIVE, $date, $date);
return $this->redirect(['action' => 'view', $project_id]);
}
}
What I need is that I want to make this two insertion action in a transaction so that if second insertion is failed anyhow, the first insertion in Projects table should roll back. Thank in advance for the help...

CakePHP 3 Between two date

I try to do an query in my controller, I want find all entity where the start and en date are between NOW(),
if $start and $end are between NOW() so show all entity, but i didn't succeed
My find is :
$day = date('l');
$now = Time::now();
$tvs = $this->Tvs
->find('all')
->contain(['Users'])
->where(['Tvs.day' => $day])
->andWhere(function($exp) {
return $exp->between($now, 'Tvs.start', 'tvs.end', $now);
});
How make this query ?
Thanks for you'r help !
Assuming you are trying to find all twhe record having $now between start and end the query is
sice the manual says that the first argument of the between fucntion should be name of the field (so it can't be a date) instead of between you can use two comparison
$tvs = $this->Tvs
->find('all')
->contain(['Users'])
->where(['Tvs.day' => $day])
->andWhere(function($exp) use($now) {
$exp->lte('Tvs.start', $now);
$exp->gte('Tvs.end', $now);
return $exp;
});
anyway you can make use of the mysql NOW() function directly into the query if the $now variable contains the same value of the NOW() function
->andWhere(function($exp, $q) {
return $exp->between($q->func()->now(), 'Tvs.start', 'Tvs.end');
});
there's anothe method: you can use BETWEEN and a palceholder to bind the value of $now
->andWhere([':now BETWEEN Tvs.start AND Tvs.end'])
->bind(':now', $now, 'datetime');
or using cakephp sql functions
->where(function($exp, $q) {
return $exp->between(':now', 'Tvs.start', 'Tvs.end');
})
->bind(':now', $now, 'datetime');
Since CakePHP 3.6 you can use identifiers:
return $query->where(function ($exp, $q) {
$today = $q->func()->now();
$start = $q->identifier('Tvs.start');
$end = $q->identifier('Tvs.end');
return $exp
->between($today,$start,$end);
});

Preserve Order of IN in ORM Order

I'm trying to do a query where I preserve the order of the ids in a IN statement. I can't seem to do it with either the Model Manage Query Builder or the standard ORM 'order' array parameter. Am I missing something? I keep getting:
UNEXPECTED TOKEN IDENTIFIER(, NEAR TO 'id`enter code here`,17743,16688,16650
Here's my model manager:
$query = $this->modelsManager->createQuery('SELECT * FROM Projects WHERE id IN ('.implode(',', array_keys($finalIterations)).')
ORDER BY FIELD(id,'.implode(',', array_keys($finalIterations)).'');
It's pretty obvious PhQL doesn't like the FIELD key word. Is there a way for me to do what I'm trying to do with PhQL? It seems I will not be able to do what I need to.
Unfortunately as previously said, this is missing a feature in Phalcon.
Have a look at this function, I've put it into my ModelBase abstract class which is parent class of all my models. It uses PhQL variable binding, so it's safe for handling direct user input.
You could have reimplemented custom \Phalcon\Mvc\Model\Criteria but this solution seems to be easier to work with, at least for me.
ModelBase abstract
public function appendCustomOrder( \Phalcon\Mvc\Model\CriteriaInterface &$criteria, $orderField, array &$orderValues = [] ) {
if(!empty($orderValues)) {
$queryKeys = $bindParams = [];
foreach($orderValues as $key => $id) {
$queryKey = 'pho'.$key;
$queryKeys[] = ':'.$queryKey.':';
$bindParams[$queryKey] = $id;
}
// TODO: add support for multiple orderBy fields
$criteria->orderBy('FIELD('.$orderField.','.implode(',',$queryKeys).')');
// there's no 'addBind' function, need to merge old parameters with new ones
$criteria->bind( array_merge( (array) #$criteria->getParams()['bind'], $bindParams ) );
}
}
Controller usage
$projectIDs = [17743, 16688, 16650];
$projectsModel = new Projects();
$criteria = $projectsModel->query->inWhere( 'id', $projectIDs );
$projectsModel->appendCustomOrder( $criteria, 'id', $projectIDs );
$projectsData = $criteria->execute();
This will generate valid PhQL syntax similar to this one:
SELECT `projects`.`id` AS `id`, `projects`.`title` AS `title`
FROM `projects`
WHERE `projects`.`id` IN (:phi0, :phi1, :phi2)
ORDER BY FIELD(`projects`.`id`, :pho0, :pho1, :pho2)

sql update codeigniter

I am using codeIgniter..
I want to update a table column is_close when id=$ticket_id of my table= tbl_tickets.
I am doing this :-
$data=array(
'is_close'=>1
);
$this->db->where('id',$title_id);
$this->db->update('tbl_tickets',$data);
and I have also done this :-
$sql = "UPDATE tbl_tickets SET is_close={1} WHERE id='$title_id'";
$this->db->query($sql);
both are not working,i.e., my table is not updating the value to 1 and also no error is being shown in the broswer. :(
Edited: Included my model part :
function setClosePost($title_id){
$sql = "UPDATE tbl_tickets SET is_close=0 WHERE id='$title_id'";
$this->db->query($sql);
// $data=array(
// 'is_close'=>1
// );
// $this->db->where('id',$title_id);
// $this->db->update('tbl_tickets',$data);
}
My controller :-
function closePost(){
$this->load->model('helpdesk_model');
$this->helpdesk_model->setClosePost($this->input->post('title_id'));
}
first of all use a get method to check if ticket_id is exist or not.
another thing is always use return in your functions in models so you can check them by if(function_name){...}else{...}
then if your get method returned data correctly try
Model Method
public function set_closed($ticket_id){
$this->db->set(array(
'is_close'=>1
)); // pass fields in array
$this->db->where('id',$ticket_id);
$this->db->update('tbl_tickets'); // table name
return true;
}
then check that in your controller
if($this->Ticket_model->set_closed($ticket_id) == true){
echo 'ticket set to closed correctly';
}else{
echo 'there is some error on updating database'.$this->db->error(); // to checkout db error .
}
First, check $title_id before passing:
var_dump($title_id);
Then, try do "select a row with this id" before updating and after.
$query = $this->db->get_where('tbl_tickets', array('id' => $id));
foreach ($query->result() as $row)
{
var_dump($row->is_close);
}
$data=array(
'is_close'=>1
);
$this->db->where('id',$title_id);
$this->db->update('tbl_tickets',$data);
$query = $this->db->get_where('tbl_tickets', array('id' => $id));
foreach ($query->result() as $row)
{
var_dump($row->is_close);
}
Then, give your table structure.
Just try like this
$sql = "UPDATE tbl_tickets SET is_close='1' WHERE id=".$title_id;
$this->db->query($sql);
just try like this
**function edit($close,$id) {
$sql = "UPDATE tbl_tickets SET is_close= ? WHERE id = ? ";
$this->db->query($sql, array($close,$id));
}**
To handle this type of errors, i mean if reflection is not happen in database, then use below steps to resolve this type of error.
1) use $this->db->last_query() function to print query, using this we can make sure our variable have correct value (should not null or undefined), using that we can make sure also SQL query is valid or not.
2) If SQL query is valid then open phpmyadmin & fire same query into phpmyadmin, it will return error if query columns or table names are invalid.
Use this way, its best way to cross check our SQL queries issues.
I hope it will work.
Thanks
You are trying to update integer(INT) type value, just cross check with your column datatype if that is varchar then you have to put value in a single or double quote.
Like this
$data=array('is_close'=> '1');

MySQL: Query Cacheing (How do I use memcache?)

I have an query like:
SELECT id as OfferId FROM offers
WHERE concat(partycode, connectioncode) = ?
AND CURDATE() BETWEEN offer_start_date
AND offer_end_date AND id IN ("121211, 123341,151512,5145626 ");
Now I want to cache the results of this query using memcache and so my question is
How can I cache an query using memcache.
I am currently using CURDATE() which cannot be used if we want to implement caching and so how can I get current date functionality without using CURDATE() function ?
Something like this should work:
function getOffers($ids) {
$key = implode(',', $ids);
$cache = new Memcache();
$cache->connect('localhost');
$content = $cache->get($key);
if ($content === false) {
// content is not cached, so we have to run the query
$content = $yourDb->query('your query here');
$cache->add($key, $content);
}
$cache->close();
return $content;
}
getOffers(array('121211','123341','151512','5145626'));
You can take this a step further by sorting $ids so that the same "set" of IDs (but in a different order) will still take advantage of an available cache for that set.
This isn't date-sensitive, but you can make it date sensitive by adding the date string to $key