Laravel Livewire 更新深层嵌套模型

Laravel Livewire update deep nested Model

我创建了一个包含几个深层嵌套关系的 Livewire 表单。我如何在提交时更新 livewire 中的这种关系?

这是我的尝试:

class ProfileForm 扩展组件 {

use WithFileUploads;

public $upload;
/**
 * @var
 */
public User $user;

/**
 * @var
 */
public $specialistations;

/**
 * @var
 */
public $occupationGroups;

/**
 * @var
 */
public $professionGroups;



protected array $rules = [
    'user.account.company' => ['integer', 'nullable'],
    'user.account.specialisations' => ['nullable', 'array'],
    'user.account.professions' => [],
    'user.account.occupations' => ['nullable', 'array'],
    'user.account.about' => ['string', 'nullable'],
    'user.account.company_addon' => ['nullable'],
    'user.account.company_phone' => ['nullable'],
    'user.account.company_email' => ['email', 'nullable'],
    'user.account.phone' => ['nullable'],
    'user.account.published' => ['nullable'],
    'user.account.web' => ['nullable'],
    'user.account.company_fax' => ['nullable'],
    'user.account.fax' => ['nullable'],
    'user.account.email' => ['email'],
    'upload.*' => 'image|max:1024',
];


/**
 * @return void
 */
public function mount()
{
    $user = auth()->user()->load(['account', 'account.specialisations']);
    $this->specialistations = Specialisation::get();
    $this->occupationGroups = OccupationGroup::get();
    $this->professionGroups = Profession::get();
    $this->user = $user;
}

public function submit()
{
    if($this->upload) {
        $this->user->avatar = $this->upload->store('files', 'public');
    }

    $this->user->update();
    $this->user->account->update();
}


public function render()
{
    return view('livewire.profile-form');
}

}

根据Livewire docs - nested data,您可以保存相关模型


public function submit()
{
    if($this->upload) {
        $this->user->avatar = $this->upload->store('files', 'public');
    }

    $this->validate();

    $this->user->save();
    $this->user->account->save();
}
更新:(对于将来访问的任何人)

the problem is that $this->user->account is having other relations and the save will fail with SQLSTATE[42S22]: Column not found: 1054 Unknown column 'professions' in 'field list'

正如 OP-@fefe 自己所指出的,确保加载所有关系(所有使用的关系,在组件中更新)。

mount()方法中

public function mount()
{
    $user = auth()->user()->load([
        'account', 
        'account.specialisations',
        'account.professions',
        'account.occupations',
    ]);

    $this->specialistations = Specialisation::get();
    $this->occupationGroups = OccupationGroup::get();
    $this->professionGroups = Profession::get();
    $this->user = $user;
}
选项二(更好)

将组件分成两部分:一个用于用户,另一个组件用于用户帐户。

然后在UserAccount组件中处理保存所有账户关系。如果关系只嵌套一层那么应该不是问题。