Codeigniter 4 while unlinking shows the error: Trying to access array offset on value of type null

Codeigniter 4 while unlinking shows the error: Trying to access array offset on value of type null

进入我在 Codeigniter 4 中的项目我想从数据库中删除记录以及我想取消链接到该记录的文件但是它给了我

的错误
Trying to access array offset on value of type null

到现在为止我已经尝试过了,但是它没有按照我想要的方式工作,下面是我的代码



public function delete($id = null)
{

    $model = new AbcModel();
    

    try{
        $id=$this->request->getPost('id');
        $this->record = $model->where('id', $id)->first();
        $image = $this->record['image'];

        if(unlink('.'.$image)){
            $model->where('id', $id)->delete();
            echo "delete";

        }
        

        
    }
    catch(\Exception $e){
        echo $e->getMessage();
    }
}
}

我的模型

<?php namespace App\Models;
 
class AbcModel extends MyModel
{

protected $table = 'abc';
protected $primaryKey = 'id';

}

进入数据库我将文件保存为/public/uploads/abcfolder/Tulips.jpg

我认为您的删除查询有问题,而不是取消链接,所以您收到了 Trying to access array offset on value of type null 的错误。所以我已经纠正了你的代码尝试一次

$id=$this->request->getPost('id');
$model = new CurriculumModel();
$record = $model->find($id);
$image = $record['image'];

$file='.'.$image;
if(is_file($file))
{
    unlink($file);
    $model->delete($id);
    echo 'delete';
}

这段代码对我有用,我不确定它是否适合你,但试一试。

所以很喜欢我


<?php namespace Modules\Common\Libraries;

use CodeIgniter\HTTP\Response;

class  CustomFile
{
    protected string $error;

    public function __construct()
    {
        $this->error = '';
    }

    /**
     * @return string
     */
    public function getError(): string
    {
        return $this->error;
    }

    public function removeSingleFile( $path)
    {
        try {

            if (file_exists($path)) {
                unlink($path);
            }


        } catch (\Exception $e) {
            $this->error = $e->getMessage();

        }

    }


    


}

在您的 ctl 或服务中

/**
     * edit function
     * @method : DELETE with params ID
     * @param $id
     * @param $foreignKey
     */
    public function delete($id)
    {


$cfs  = new  CustomFile();
$model = new MyModel();

            $deleteById = $model->where(['id' => $id])->findAll();
          
        

        if (is_null($deleteById)) $this->httpException(lang('Shared.api.exist'), ResponseInterface::HTTP_NOT_FOUND);


        $model->where(['id' => $id])->delete();

        foreach ($deleteById as $path) {

            $cfs->removeSingleFile(ROOTPATH . $path->path);
        }


    }