php - 如何使用 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');
}
}
解决方案
为什么不只是:
CalendarEvent::where('id', $request->appointmentId)->delete();
另外,检查 deleted_at 列。如果它不为 null,则 select 将返回 null,除非您添加 ->withTrashed() 方法。
当使用 Eloquent 对象时,使用 SoftDelete trait,当直接使用 DB:: 时,则不使用 SoftDelete trait。
推荐阅读
- maven - 如何将maven项目创建为其他项目的依赖jar而不依赖于其他项目
- java - Navigation Drawer Activity:在片段之间传递值
- html - Bootstrap Grid 不会填满空的地方
- java - 如何从这样的 JSON 响应中获取值
- android - 导航架构组件:FragmentManager 已经在执行事务
- python - 使用 kivy 使用另一个复选框选中或取消选中复选框
- javascript - 剑道网格中的最小列宽
- azure - azure devops how can i make a pipeline that will update 2 branches?
- adonis.js - Adonis:如何使用 SSL(带有 certificate.crt 文件)连接到 MySQL?
- reactjs - 不重定向到 React JS 中指定的路径