【问题标题】:Call to undefined method CodeIgniter\Database\MySQLi\Builder:: find()调用未定义的方法 CodeIgniter\Database\MySQLi\Builder:: find()
【发布时间】:2021-05-08 10:26:40
【问题描述】:

我正在制作 CRUD,上传文件(图像),但是当我想使用取消链接删除文件时出现错误,如下所示。

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

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

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 行删除文件,我可以'不是因为有错误。

【问题讨论】:

  • 错误告诉你find方法不存在。我建议查看 CodeIgniter 文档以了解获取行的正确方法。

标签: php codeigniter codeigniter-4 unlink


【解决方案1】:

Exception 表示 $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
}

【讨论】:

    猜你喜欢
    • 2021-02-02
    • 2020-09-22
    • 2014-04-23
    • 2020-01-04
    • 2021-10-18
    • 2018-10-03
    • 1970-01-01
    • 2019-04-02
    • 2016-11-25
    相关资源
    最近更新 更多