首页 > 解决方案 > Wire:model 未显示从 Array Pivot 表中选择的值

问题描述

当我尝试在 laravel 上的多对多关系上更新/更改数据透视表时遇到问题。我已经从数据透视表中检索到数据,并希望将其显示为在选择输入中选择的,但它似乎不起作用。这里的表: 多对多表

军官模型范围根据类别返回特定头衔:

public function scopeFilterByCategory(Builder $query, $type = 'spv')
{
    return $query->select('id', 'name', 'title_id')->with('title')
        ->whereHas('title', function (Builder $query) use ($type) {
        $query->where('category', '=', $type); })->get();
}

项目 livewire 组件:

class DataProject extends Component
{
    //Person in Charge
    public $pic = [];

    public Project $project;
    //rest of codes

    public function save()
    {
        $this->project->save();
        $data_pic = Arr::flatten($this->pic);
        $this->project->officers()->attach($data_pic);
    }

    public function showUpdateModal(Project $project)
    {
        if ($this->project->isNot($project)) $this->project = $project;
        //Retrieve officers assigned to project
        foreach ($project->officers as $person) {
            $this->pic[] = $person->id;
        }
    }

    public function render()
    {
            return view('livewire.project.data-project', [
                'dataProject' => $this->rows,
                'spv' => Officer::filterByCategory() //scope func
                'manager' => Officer::filterByCategory('mgr')
            ]);
    }
}

取自更新/编辑模式的刀片视图形式:

<select wire:model="pic.0" class="custom-select">
    @foreach ($spv as $person)
    <option value="{{ $person->id }}">{{ $person->name }}</option>
    @endforeach
</select>

<select wire:model="pic.1" class="custom-select">
    @foreach ($manager as $mgr)
    <option value="{{ $mgr->id }}">{{ $mgr->name }}</option>
    @endforeach
</select>

假设我们在wire:model="pic.0" 上选择officer id 5,在wire:model="pic.1" 上选择oficcer_id 1。结果:

$pic = array[
    0 => 5,
    1 => 1,
];

当我保存模型并将 pic[] 属性附加到 project_officer 表时,一切都很好并保存了。当我尝试更新/更改分配的人员时,问题出现了,我的 SELECT 输入没有显示从 PIC [] 属性中选择的人员(包含来自查询的数据),即使我使用 Wire:model 来绑定属性。仅选择输入选择默认选项(第一行)。当我有更多的官员名单时,情况会更糟。我的期望是当 PIC[] 属性填充来自查询的数据时,SELECT 输入从 PIC[] 中选择值,并显示为选中状态。任何解决方法可以使 PIC 中的值显示为表格中的选择?

标签: phplaravellaravel-livewire

解决方案


推荐阅读