Я столкнулся с проблемой Livewire, из-за которой атрибуты, установленные с помощью методов setAttribute() и setRelation() в методе mount(), отсутствуют после отправки формы.< /p>
Признак: HasEloquentModel
trait HasEloquentModel
{
#[Locked]
public ?Model $model = null;
public function getModel()
{
if (isset($this->model)) {
if ($this->model instanceof Model) {
return $this->model;
}
return app($this->model);
}
return str(class_basename(static::class))->beforeLast('Component')->prepend('App\\Models\\')->toString();
}
}
Компонент Livewire: AssigneeFormComponent
use HasEloquentModel;
public function mount($slug, $id)
{
$assignee = app(AssigneePost::class); // Pivot Table
$post = app(Post::class);
$currentRouteName = Route::currentRouteName();
if($currentRouteName === 'assignees.create') {
$post = $post->query()->where(compact('slug', 'id'))->firstOrFail();
$assignee->setRelation('post', $post);
$assignee->setAttribute('post_id', $post->id);
$assignee->setAttribute('user_id', auth()->id());
} elseif($currentRouteName === 'assignees.edit') {
$assignee = $assignee->query()->with('post')
->where('id', $id)
->whereRelation('post', 'slug', '=', $slug)
->firstOrFail();
}
$this->model = $assignee;
//...
}
public function attemptSubmit()
{
$validated = $this->validate();
$this->getModel()->fill($validated)->save();
//...
}
При редактировании формы поля post_id и user_id остаются неизменными. Однако для новой формы Assignee мы получаем post_id и user_id из метода mount(), тогда как вне его они остаются неизменными. Форма содержит такие поля, как контент, тип, статус, утвержденный_at, утвержденный_по и т. д., проверяемые после отправки формы. После успешной отправки все поля, включая post_id и user_id, сохраняются в базе данных. Но я столкнулся с ошибкой:
SQLSTATE[HY000]: Общая ошибка: 1364 Поле «post_id» не имеет
значения по умолчанию< /p>
Когда я dd($this->getModel()) после отправки формы, атрибуты пользовательского набора отсутствуют.$assignee->setRelation('post', $post); // -----------> Missing
$assignee->setAttribute('post_id', $post->id); // -----------> Missing
$assignee->setAttribute('user_id', auth()->id()); // -----------> Missing
Подробнее здесь: https://stackoverflow.com/questions/783 ... er-form-su