首页 > 解决方案 > 如何使用 Eloquent 查询删除数据?

问题描述

我无法使用简单的 eloquent 查询删除一行。即使我使用 eloquent 也无法从数据库中获取数据。我越来越空了。但是,在数据库查询方法中,至少我正在获取数据但不能删除。以下是我的代码:

DB::transaction(function () use ($lead, $comment, $request) {
    $lead->save();
    $lead->comments()->save($comment);

    if ($request->deleteAppointment) {
        $calendarEvent = DB::table('calendar_events')->where('id', $request->appointmentId)->first(); // I am getting data here.
        $calendarEvent = CalendarEvent::find($request->appointmentId); // But, here I am getting null, don't know why!
        
        if ($calendarEvent != null) {
            $calendarEvent->delete();
        }
    } 

我的目标是使用 Eloquent 获取数据,然后从数据库中删除。

更新:我的数据库表 在此处输入图像描述

CalendarEvent.php 模型

class CalendarEvent extends Model
{
    use SoftDeletes;

    /**
     * @var array
     */
    protected $casts = [
        'event_begin' => 'datetime',
        'event_end'   => 'datetime',
        'options'     => 'array',
    ];

    /**
     * @var array
     */
    protected $guarded = [
        'id',
    ];

    /**
     * @return mixed
     */
    public function users()
    {
        return $this->morphedByMany(User::class, 'eventable');
    }

    /**
     * @return mixed
     */
    public function attendees()
    {
        return $this->morphedByMany(User::class, 'eventable')->withPivotValue('role', 'atendee');
    }

    /**
     * @return mixed
     */
    public function companies()
    {
        return $this->morphedByMany(Company::class, 'eventable')->withPivotValue('role', 'company');
    }

    /**
     * @return mixed
     */
    public function invitees()
    {
        return $this->morphedByMany(User::class, 'eventable')->withPivotValue('role', 'invitee');
    }

    /**
     * @return mixed
     */
    public function leads()
    {
        return $this->morphedByMany(Lead::class, 'eventable')->withPivotValue('role', 'lead');
    }
}

标签: phplaraveleloquent

解决方案


为什么不只是:

CalendarEvent::where('id', $request->appointmentId)->delete();

另外,检查 deleted_at 列。如果它不为 null,则 select 将返回 null,除非您添加 ->withTrashed() 方法。

当使用 Eloquent 对象时,使用 SoftDelete trait,当直接使用 DB:: 时,则不使用 SoftDelete trait。


推荐阅读