php - 在 OctoberCMS 的 PHP 数据库中保存模型属性

标签 php database attributes save

您好,当我尝试将模型的属性保存到数据库时遇到问题。我在 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/

相关文章:

mysql | mysql |具体要求

c - 我如何确定此 C 结构在 32 位和 64 位系统上均已打包? "__attribute__((packed))"总是必要的吗?

attributes - 通过 PHP 代码添加 WooCommerce 属性

javascript - 自定义表单和 DropZoneJS

php - Phil Sturgeons php codeigniter rest api 中的方法特定身份验证

php - 是否有与 PHP 函数 htmlspecialchars() 等效的 Python?

php - php 和 mysql 中的 while 和 if 语句

android - Android 中的 MySQL 数据库

mongodb - 如何计算 MongoDB 中多个 GeoJSON 点之间的路线距离?

python - 按名称引用对象作为属性