Moe Sweet
Moe Sweet

Reputation: 3721

How do I update 1 field in CakePHP?

I want a function to alter one field, "is_featured" to 1(true) of Event model of given ID, to mark an event as "Featured".

class EventsController extends AppController{
function feature($id){}
}

Upvotes: 32

Views: 62601

Answers (7)

A.A Noman
A.A Noman

Reputation: 5270

You can do this easy way

$this->Event->saveField('username', $user); //Where username is Model field name and $user is value

Upvotes: 0

ptica
ptica

Reputation: 747

strangely; sometimes I like to resort for plain old sql: one-liner + no overhead there, makes me sure no callbacks/events get involved (beware this may be not what you want!)

$id = (int) $id;
$this->Event->query("UPDATE events SET is_featured=1 WHERE id=$id");

Upvotes: -3

Leonardo Correa
Leonardo Correa

Reputation: 300

In cakephp 3 to update your data:

  1. Include in your Controller:

    use Cake\ORM\TableRegistry;

  2. In your action:

    $articlesTable = TableRegistry::get('Articles');
    $article = $articlesTable->get(12); // Return article with id 12
    
    $article->title = 'CakePHP is THE best PHP framework!';
    $articlesTable->save($article);
    

Source: http://book.cakephp.org/3.0/en/orm/saving-data.html

Upvotes: 4

Shinigami
Shinigami

Reputation: 77

You can use this technique to update the field(s)

$this->Event->save($this->request->data, true, array('id', 'is_featured'))

If you don’t want the modified field to be automatically updated when saving some data add 'modified' => false to your $data array If you don’t pass the id, the model cannot set its primary key and will “add” instead of “edit” the field(s)

Upvotes: 1

Dimpal Gohil
Dimpal Gohil

Reputation: 219

You can also use set() method

$this->Model->read(null, $id);
$this->Model->set(array(
      'fieldname' => 'value',
));
$this->Model->save();

Upvotes: 12

dqminh
dqminh

Reputation: 1585

you can use saveField to do this for example

$this->Event->id = $id;
$this->Event->saveField('is_featured', true);

Upvotes: 75

Vineet Kumar
Vineet Kumar

Reputation: 187

You can perform update in one field by two ways:

    $this->Model->id=$id;
    $this->Model->saveField("fieldName","value");

OR

    $this->Model->updateAll(array("fieldName"=>"value"),array("fieldName"=>"condition"));

in second example, first array will update the value in defined field and second array defines the "WHERE" condition

Upvotes: 12

Related Questions