[英]How to delete data using Eloquent query?
我無法使用簡單的 eloquent 查詢刪除一行。 即使我使用 eloquent 也無法從數據庫中獲取數據。 我得到 null。但是,至少在數據庫查詢方法中我正在獲取數據但無法刪除。 以下是我的代碼:
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 model
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 特性,當直接使用 DB:: 時,則不使用 SoftDelete 特性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.