我正在使用一个特征来动态地将电子邮件属性添加到模型中。它使我能够在许多模型中重用代码。但是,当我尝试创建新模型时,此代码失败(但当我更新现有模型时,该代码会成功)。 问题是假设
$this->id在 Traits/Contact/HasEmails > setEmailTypeAttribute 中可用。 Id 尚不可用,因为保存尚未完成。 我的问题:我怎样才能修复这个特性,使其在创建模型时也能工作?
谷歌,没有结果 思考一些模型事件 (static::creating($model))
pp\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]);
}
pp\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);
}
}
\migrations�9_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');
});
我希望创建/更新相关模型,但创建失败。
/*
* 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
]);
});
}