【问题标题】:Laravel: How do i fix this trait (with attributes) to also work when creating a model?Laravel:我如何修复这个特征(带有属性)在创建模型时也可以工作?
【发布时间】:2020-02-15 11:53:24
【问题描述】:

我正在使用 trait 将电子邮件属性动态添加到模型中。它使我有可能在许多模型中重用代码。但是,当我尝试创建新模型时,此代码会失败(但当我更新现有模型时成功)。

问题是假设 $this->id 在 Traits/Contact/HasEmails > setEmailTypeAttribute 中可用。 ID 尚不可用,因为尚未完成保存。

我的问题:我怎样才能修复这个特性,以便在创建模型时也能正常工作?

谷歌,没有结果 思考一些模型事件(static::creating($model))

\app\Traits\Contact\HasEmails.php


 /*
     * EmailGeneric getter. Called when $model->EmailGeneric is requested.
     */
    public function getEmailGenericAttribute() :?string
    {
        return $this->getEmailTypeAttribute(EmailType::GENERIC);
    }

    /*
     * EmailGeneric setter. Called when $model->EmailGeneric is set.
     */
    public function setEmailGenericAttribute($email)
    {
        return $this->setEmailTypeAttribute(EmailType::GENERIC, $email);
    }

     /*
     * Get single e-mail model for model owner
     */
    private function getEmailTypeAttribute($emailType) :?string
    {
        $emailModel = $this->emailModelForType($emailType);
        return $emailModel ? $emailModel->email : null;
    }

    /*
    * Update or create single e-mail model for model owner
    *
    * @return void
    */
    private function setEmailTypeAttribute($emailType, $email) :void
    {
        $this->emails()->updateOrCreate([
            'owned_by_type' => static::class,
            'owned_by_id' => $this->id,
            'type' => $emailType
        ],['email' => $email]);
    }

\app\Models\Email.php


namespace App\Models;

class Email extends Model
{

    public $timestamps = false;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'email'
    ];

    /*
     * Get polymorphic owner
     */
    public function ownedBy(): \Illuminate\Database\Eloquent\Relations\MorphTo
    {
        return $this->morphTo();
    }

    /*
     * Default attributes are prefilled
     */
    protected function addDefaultAttributes(): void
    {
        $attributes = [];
        $attributes['type'] = \App\Enums\EmailType::GENERIC;

        $this->attributes = array_merge($this->attributes, $attributes);
    }
}

\迁移\2019_10_16_101845_create_emails_table.php

 Schema::create('emails', function (Blueprint $table) {
            $table->bigIncrements('id');

            $table->unsignedBigInteger('owned_by_id');
            $table->string('owned_by_type');

            $table->string('type');              //f.e. assumes EmailType
            $table->string('email');

            $table->unique(['owned_by_id', 'owned_by_type', 'type'], 'owner_type_unique');
        });

我希望创建/更新相关模型,但创建失败。

【问题讨论】:

    标签: laravel dynamic model save


    【解决方案1】:

    Trick 正在使用已保存的模型事件,并且还没有忘记在电子邮件模型上设置可填充属性:

    /*
        * Update or create single e-mail model for model owner
        *
        * @return void
        */
        private function setEmailTypeAttribute($emailType, $email) :void
        {
            static::saved(static function($model) use($emailType, $email) {
                $model->emails()
                    ->updateOrCreate(
                        [
                            'owned_by_type' => get_class($model),
                            'owned_by_id' => $model->id,
                            'type' => $emailType
                        ],
                        [
                            'email' => $email
                        ]);
                });
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-27
      • 1970-01-01
      • 1970-01-01
      • 2015-02-11
      • 2018-08-20
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      相关资源
      最近更新 更多