【问题标题】:delete function not working cakephp删除功能不起作用 cakephp
【发布时间】:2013-08-01 20:45:58
【问题描述】:

我正在开发 Cakephp 2.x ...我想从数据库中删除一条记录 我的数据库中有一个名为 Image 的表 .. 其中包含以下字段.. idImage,User_id,filename,filesize,filemime

我想删除 idImage=imageid 的单条记录

      delete * from posts where imageid = 3'

我正在这样做 ..image id 现在的值为 4

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

但代码不起作用。不从数据库中删除记录

【问题讨论】:

  • 您在哪里定义imageId。如果您回显或打印imageId,您是否得到正确的值“4”?
  • 我正在从我的视图页面获取一个参数到我的控制器函数中,并且我成功获取了 4 的 id ...
  • 另外,您是否指定imageId 作为模型中的主键?默认情况下,Cake 将使用id 作为主键。在你的模型中写var $primaryKey = 'imageId';
  • 不,我没有指定它.. 好的,让我试试
  • 我试过了还是不行

标签: cakephp cakephp-2.0 cakephp-2.1


【解决方案1】:

id,不是 imageId

在 Image 模型上设置 imageId 将完全没有效果。如果模型的主键不是id,则需要configure the model,以便Cake 意识到这一点并将使用您选择的主键字段而不是id

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

无论主键的值如何,设置为使用问题中的语法的属性是:

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

这将尝试删除具有给定$imageId 的图像。

或者只是pass it to the delete function:

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

不带主键删除

如果目标是按非主键的值删除,请先查找它:

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

或使用deleteAll:

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

【讨论】:

  • 我的数据库中有 imageId 主键,并且我在模态中也指定了
猜你喜欢
  • 1970-01-01
  • 2018-07-17
  • 2018-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-20
  • 1970-01-01
相关资源
最近更新 更多