2

I have multiple rows in database.

I need to collect all the rows based on certain condition and change the value of particular column by removing a word from the column's value.

How it could be done with with CakePHP 3?

MasterAM
  • 16,283
  • 6
  • 45
  • 66
karthik
  • 161
  • 10

2 Answers2

1

Try the following:

$model->updateAll(
        ['description' => "REPLACE (description, 's', 'a')"], // fields
        ['is_disabled' => 1] //condition
);

This will generate the following sql:

UPDATE 
    mytable
SET 
    description =  REPLACE (description, 's', 'a') 
WHERE
     is_disabled = 1

Note that this is replacing the matching string ('s') everywhere where it appears in the description field - even in the middle of a word. This often leads to wellknown clbuttic mistakes.

AD7six
  • 63,116
  • 12
  • 91
  • 123
Krunal Dave
  • 272
  • 6
  • 16
  • `change the value of particular column by removing a word from the column's value.` The updateAll call in this answer doesn't do that, or make it apparent how it could be changed to do that. – AD7six Oct 15 '15 at 08:54
  • I've amended the answer so that it answers the question - in future it is a better idea to only write an answer, if it does actually answer the question. Thanks for using whitespace in your code examples - please do keep up that habit (and fix your existing questions/answers which don't do this). – AD7six Oct 15 '15 at 09:35
  • "REPLACE (description, 's', 'a')" totally this values are updated into my columns – karthik Oct 15 '15 at 09:40
0

Add this on top of the controller "use Cake\Datasource\ConnectionManager;"

$this->loadModel('Rewards');
$connection = ConnectionManager::get('default');
$results = $connection->execute("UPDATE rewards SET description =  REPLACE (description, 's', 'a') where is_disabled=1");

I have values in description fields 'wwss' now that fields word replace into 'wwaa' like that.

For more explanation refer this link

http://book.cakephp.org/3.0/en/orm/database-basics.html

How can I use mySQL replace() to replace strings in multiple records?

Please review,Thanks!

Community
  • 1
  • 1
karthik
  • 161
  • 10
  • 1
    Why are you answering your own question as if you don't know the person who asked the question? – AD7six Oct 15 '15 at 08:56
  • @AD7six Hi 1st searched the answer for this question and got the answer from the document it works perfect to me.so i post the answer for my question – karthik Oct 15 '15 at 09:26
  • Answering your own question is great (and encouraged) adding this when self answering is quite bizarre `I hope this is usefull for your question.Please review,Thanks!` – AD7six Oct 15 '15 at 09:28
  • @AD7six i am sry. it's my careless :) Now i edit and updated my question – karthik Oct 15 '15 at 09:36