在 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
uj5u.com熱心網友回復:
我認為您的洗掉查詢有問題,而不是取消鏈接,因此您收到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';
}
這段代碼對我有用,我不確定它是否對你有用,但試試看。
uj5u.com熱心網友回復:
所以它喜歡我
<?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);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/423099.html
標籤:
