1
votes

i am working on a Cakephp 2.x ...i want to delete a single record from the database i have a table in my database called Image .. which contain following fields.. idImage,User_id,filename,filesize,filemime

I would like to delete the single record with idImage=imageid

      delete * from posts where imageid = 3'

i am doing this ..image id now has a value 4

      $this->Image->imageId = $imageId;
if($this->Image->delete()){
        echo "successfull";
    }else{
            echo "not";
        }

but the code is not working .not deleting the record from db

1
where is it that you are defining imageId. If you echo or print imageId are you getting the correct value "4"?bowlerae
i am getting a parameter from my view page into my controller function and i am successfully getting the id which is 4 ...hellosheikh
also, did you specify imageId as the primary key in the model? By default Cake will use id as the primary key. In your model write var $primaryKey = 'imageId';bowlerae
nope i didnt specify it .. ok let me tryhellosheikh
i try but still didnt workhellosheikh

1 Answers

4
votes

id, not imageId

Setting imageId on the Image model will have no effect at all. If the model's primary key is not id it's necessary to configure the model so that Cake is aware of this and will use your chosen primary key field instead of id.

<?php
class Image extends AppModel {
    $primaryKey = 'imageId';

Irrespective of the value of the primary key, the property to set to use the syntax in the question is:

$this->Image->id = $imageId;
if($this->Image->delete()){

This will attempt to delete the image with the given $imageId.

Alternatively just pass it to the delete function:

if($this->Image->delete($imageId)){

Deleting without a primary key

If the objective is to delete by a value that isn't the primary key, either look for it first:

$id = $this->Image->field('id', array('imageId' => $imageId));
if ($id && $this->Image->delete($id)) {
    ...

Or use deleteAll:

// delete 1 or more records with a matching field value
$this->Image->deleteAll(array(
    'imageId' => $imageId
));