【发布时间】: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 现在,我明白了。我其实不知道软删除!现在,我明白了问题所在。它已经被删除了!我的错。