【问题标题】:How to delete data using Eloquent query?如何使用 Eloquent 查询删除数据?
【发布时间】:2021-01-29 20:59:05
【问题描述】:

我无法使用简单的 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');
    }
}

【问题讨论】:

  • 您似乎在使用软删除。您的模型可能已被软删除,但这在通过DB 获取时不会反映出来,因为模型上有软删除特征。检查deleted_at 是否不为空
  • 请提供您的CalendarEvent.php 文件,并确认该记录没有deleted_at 时间戳
  • 虽然它应该自己计算出表名,但在你的模型中声明它 protected $table = 'calendar_events';再试一次 - 看看是否能获得记录
  • 如果您说deleted_at 不为空,那么这就是您无法检索该记录的原因。
  • @SimonR 现在,我明白了。我其实不知道软删除!现在,我明白了问题所在。它已经被删除了!我的错。

标签: php laravel eloquent


【解决方案1】:

为什么不只是:

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

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

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

【讨论】:

  • 是的,它已经被删除了。我的错。我不知道 Laravel 中的软删除。
猜你喜欢
  • 1970-01-01
  • 2017-05-21
  • 1970-01-01
  • 1970-01-01
  • 2020-11-09
  • 2014-05-20
  • 2021-03-21
  • 2015-12-28
  • 2020-07-18
相关资源
最近更新 更多