top-think / think-orm

Think ORM——the PHP Database&ORM Framework
Apache License 2.0
413 stars 171 forks source link

$receiver->where('email_id', $id)->delete();怎么也不能删除#issuecomment-2252198289 #594

Closed netmou closed 1 month ago

netmou commented 1 month ago
          我也遇到了这种情况
class EmailReceiver extends BaseModel
{

    protected $name = "email_receiver";

    protected $deleteTime = "delete_time";

    public function sender(){
        return $this->belongsTo(EmailSender::class, 'email_id', 'id');
    }

}
class EmailSender extends BaseModel
{

    protected $name = "email_sender";

    protected $deleteTime = "delete_time";

    public function receiver(){
        return  $this->hasMany(EmailReceiver::class,'email_id','id');
    }
}

控制器$receiver->where('email_id', $id)->delete();怎么也删除不了

public function delete($id): void
    {
        $this->checkPostRequest();
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $receiver = new EmailReceiver();
            $receiver->where('email_id', $id)->delete();   // 这里怎么也删不了
            $save = $row->delete();
        }catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

Originally posted by @netmou in https://github.com/top-think/framework/issues/2653#issuecomment-2252198289

netmou commented 1 month ago

经过多方搜索发现

$receiver->where('email_id', $id)->delete(); // 删除不了 $receiver->where('email_id', $id)->find()->delete(); //好使 哪位大佬能解释下吗,这不是妥妥的坑吗

netmou commented 1 month ago

补充下模型基类

class BaseModel extends Model
{

    /**
     * 自动时间戳类型
     * @var string
     */
    protected $autoWriteTimestamp = true;

    /**
     * 添加时间
     * @var string
     */
    protected $createTime = 'create_time';

    /**
     * 更新时间
     * @var string
     */
    protected $updateTime = 'update_time';

    /**
     * 软删除
     */
    use SoftDelete;
    protected $deleteTime = false;

}
big-dream commented 1 month ago

为什么用软删除,然后又把deleteTime设置为 false

netmou commented 1 month ago

基类是false,下面子类看情况开启 protected $deleteTime = "delete_time";

Hhh0121 commented 1 month ago

经过多方搜索发现

$receiver->where('email_id', $id)->delete(); // 删除不了 $receiver->where('email_id', $id)->find()->delete(); //好使 哪位大佬能解释下吗,这不是妥妥的坑吗

image 看官网文档。软删除实现是重写了模型的delete的方法,必须调用模型的方法才可以,where相当于调用的数据库的方法,所以不行

netmou commented 1 month ago

$receiver->where(...) $receiver是模型实例 你告诉我where不是他的方法,但能调用,从字面上看感觉很绕,一不注意就是大坑