【问题标题】:Save attribute of model in database in PHP in OctoberCMS在OctoberCMS中将模型的属性保存在PHP中的数据库中
【发布时间】:2016-12-03 06:35:31
【问题描述】:

您好,当我尝试将模型的属性保存到数据库时遇到问题。我在 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 时它不保存在数据库中。也许有人看到我的错误?

【问题讨论】:

  • 我从来没有使用过OctoberCMS,但看起来你应该-&gt;save()你的模型,这样它才能持续存在。 octobercms.com/docs/database/model#basic-updates
  • 但我在函数 afterSave() {there is my function}中使用了这个,所以我尝试使用 ->save() 问题必须在其他地方
  • 我厌倦了使用 save() 我在我的帖子中写过这个,但它仍然没有将我的属性保存到数据库中
  • 如果您在“afterSave”回调中使用它,则保存操作已经发生。是否可以使用“beforeSave”回调?
  • 是的,我之前试过用这个保存也一样

标签: php database attributes save


【解决方案1】:

如果您尝试根据一些自定义逻辑修改模型然后保存,最好将其放置在模型的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-&gt;save() 或类似的东西。只需在 beforeSave() 方法中修改模型的属性即可完成您想要的。

【讨论】:

  • 但我在 beforeSave 中使用了它,然后它没有效果。其次,我最终不想在 beforeSave 中使用此功能,而是在 taskSchedule 中使用 cron,它应该自动在我的数据库上运行。我的意思是自动搜索具有状态的记录,如果没有具有此状态的记录,则在我的 if 语句中使用条件查找,然后覆盖该记录的 status_id。现在我在 cron 中使用这个 ->save() 但这仍然不能保存我的数据
猜你喜欢
  • 2014-11-04
  • 2011-11-03
  • 2017-12-27
  • 2017-11-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-10
  • 1970-01-01
  • 2020-07-30
相关资源
最近更新 更多