您好,当我尝试将模型的属性保存到数据库时遇到问题。我在 OctoberCMS 中编写,我有这个功能:
public function findActualNewsletter()
{
$actualNewsletter = Newsletter::where('status_id', '=', NewsletterStatus::getSentNowStatus())->first();
if (!$actualNewsletter) {
$actualNewsletter = Newsletter::where('send_at', '<=', date('Y-m-d'))->where('status_id', NewsletterStatus::getUnsentStatus())->first();
$actualNewsletter->status_id = NewsletterStatus::getSentNowStatus();
dd($actualNewsletter);
}
return $actualNewsletter;
}
getSentNowStatus()=2;
getUnsentStatus()=1;
dd($actualNewsletter) 在我的 if 语句中显示 status_id = 2 但在数据库中我仍然有 1。我在 afterSave() 中使用了这个函数所以我不需要:
$actualNewsletter->status_id = NewsletterStatus::getSentNowStatus();
$actualNewsletter->save();
因为我有错误所以我在保存中使用保存。 当然,我填写了表格 $fillable =['status_id']。现在我不知道为什么它在转到我的 if 时不保存在数据库中。也许有人看到我的错误?
最佳答案
如果您试图根据一些自定义逻辑修改模型然后保存它,最好将它放在模型的beforeSave()
方法中。要访问当前保存的模型,只需使用 $this
。下面是 beforeSave()
方法的示例,用于在将模型保存到数据库之前修改模型的属性:
public function beforeSave() {
$user = BackendAuth::getUser();
$this->backend_user_id = $user->id;
// Handle archiving
if ($this->is_archived && !$this->archived_at) {
$this->archived_at = Carbon\Carbon::now()->toDateTimeString();
}
// Handle publishing
if ($this->is_published && !$this->published_at) {
$this->published_at = Carbon\Carbon::now()->toDateTimeString();
}
// Handle unarchiving
if ($this->archived_at && !$this->is_archived) {
$this->archived_at = null;
}
// Handle unpublishing, only allowed when no responses have been recorded against the form
if ($this->published_at && !$this->is_published) {
if (is_null($this->responses) || $this->responses->isEmpty()) {
$this->published_at = null;
}
}
}
您不必运行 $this->save()
或类似的东西。只需在 beforeSave()
方法中修改模型的属性即可完成您想要的。
关于php - 在 OctoberCMS 的 PHP 数据库中保存模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38643632/