How to delete a single record with where condition in cakephp?
Asked Answered
S

3

7

I am using cakephp2. How to delete a single record with a condition ?

I have a table named posts with fields id,title,post. primary key is id. I would like to delete the single record with id=5 ?

How it possible ?

That is I wands to convert the query,

$this->query('delete * from posts where id = 5'); To cakephp ?

How this function is write on cakephp modeln named Post ?

Sheela answered 29/4, 2013 at 10:9 Comment(8)
so you want to delete all the records with id (which should be a primary key) 5??Longerich
yes. wands to delete the field with id=5Sheela
I guess what you want is to delete "a single" record with id=5. My answer below might help you.Longerich
I use that code but didnt get deleted. The page only just refreshedSheela
well first of all you don't really need to execute a query just to delete a record when you have got cakephp default function. Anyway it wont just refresh the page. Try to find what it returns? because this is the method to execute custom queries in cakephp. there is one more function buildQuery but i don't know if that could help you. Tell me one good reason you can't use the normal delete function?Longerich
how to use the normal delete function ?Sheela
i just explained that in my answer. trying reading it againLongerich
@VinodVT based on your last couple of questions here, you're trying to learn CakePHP without reading the manual. Almost all of those questions are basic examples inside the manual. We really want to assist you in learning CakePHP, but don't expect us to look things up in the manual for you. Try to read the CookBook it's also available as a free eBook so that you can read it offline on an e-reader.Kugler
L
16

You can do it like this. $this->Model->delete(5); or you can assign id to the model first and then delete it. Such as

$this->Model->id = 5;
$this->Model->delete();

If you want to execute a delete (or any other) query without a model then you should try

$db = ConnectionManager::getDataSource('default');
$db->rawQuery("DELETE FROM table WHERE id=5");
Longerich answered 29/4, 2013 at 10:13 Comment(0)
P
8

Use deleteAll().

$this->Model->deleteAll(array('Model.field_name'=>'field_value'));

OR delete by primary key:

1. $this->Model->delete(primary_key_value);

2. $this->Model->id = primary_key_value;
   $this->Model->delete();

Hope it will help someone.

Pacifa answered 20/1, 2016 at 12:21 Comment(0)
D
1
delete(int $id = null, boolean $cascade = true);

Deletes the record identified by $id. By default, also deletes records dependent on the record specified to be deleted.

Also you can apply function like in controller to delete one record

$this->Post->delete($this->request->data('Post.id'));

or if static id is known to you

$this->Post->delete(5);

please let me know if i can help you more

Donielle answered 29/4, 2013 at 11:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.