调用未定义的方法 CodeIgniter\Database\MySQLi\Builder:: find()

问题描述

我正在制作 CRUD,上传文件图片),但是当我想使用 unlink 删除文件时,出现错误,如下所示。

Codeigniter4 错误调用未定义的方法 CodeIgniter\Database\MysqLi\Builder:: find()

这是我用来尝试删除图像文件代码。从控制器连接到模型。

enter image description here

The controller:

    public function delete()
        {
            $model = new Datatablesmodal();
            $id = $this->request->getPost('product_id');
            $model->deleteProduct($id);
            return redirect()->to('/modalboot');
        }
    
    The modal:
    public function deleteProduct($id)
        {
            
            $foto=$this->db->table("formulir_pendaftaran")->find(array('product_id' => $id)); (line 1)
            unlink('/pasfoto/'.$foto['pas_foto']); (line 2)
            $this->db->table('formulir_pendaftaran')->delete(array('product_id' => $id));
            return $query;
        } 

表的id是product_id,如果我删除了第1行和第2行,我可以删除表中的数据,但不能删除仍在我目录中的图像文件,如果我使用第1行和第2行删除文件,我可以不是因为有错误

解决方法

异常表示 $db 没有名为 find() 的方法。

这是因为您没有使用模型,而是在 $this->db->table() 中使用了查询构建器。

那样你应该使用方法 getWhere(array('product_id' => $id)) 而不是 find(array('product_id' => $id));

但最好的方法是创建一个对应于名为 formulir_pendaftaran 的表的模型,然后使用该模型删除自我。

class FormulirPendaftaran extends Model
{
    protected $table      = 'formulir_pendaftaran';
    protected $primaryKey = 'product_id';

    protected $useAutoIncrement = true;
    
}

然后您的模型自动具有来自 Model 的 CRUD 方法,您可以在该模型上使用 delete() 方法:

$model = new FormulirPendaftaran();
$model->find($id)->delete();

这将从数据库中删除您的 $id 实例,但如果您还想删除图像,则需要在模型中扩展 delete() 方法:

public function delete()
{
    // your code to delete the image.
    parent::delete(); //which delete your instance from DB
}