首页 > 解决方案 > Laravel livewire 附加后看不到渲染更新

问题描述

我有一个 livewire 组件在页面上呈现两个列表。我在左侧列表中有一个按钮,可以使用附加将该项目添加到右侧列表(多对多)关系中。这是有效的,但正确的列表没有被重新渲染。然后,当我单击左侧列表中的过滤器时,右侧列表会重新呈现,显示新附加的项目。当我执行附加方法时,似乎没有调用 render() ,或者它正在再次调用 render 来获取新关系?我也尝试从 attach 方法调用 $this->render ,但这没有帮助。

public function render()
    {
        $items = item::with('status')
            ->where(function($query){
                $query->when(!empty($this->selectedStati), function ($query) {
                    $query->whereHas('status', function ($query) {
                        $query->whereIn('id', $this->selectedStati);
                    })->orWhereDoesntHave('status');
                });
            })
            ->get();

        $testItems = $this->test->items;
       //dd($testItems);
        return view('livewire.items-source', [
            'selectedStati' => $this->selectedStati,
            'statuses' => $this->status,
            'items' => $items,
            'testItems' => $testItems
    ]);
    }

    public function filterStatus($id){
        if (($key = array_search($id, $this->selectedStati)) !== false) {
            unset($this->selectedStati[$key]);
        } else {
            $this->selectedStati[]=$id;
        }
        session(['status'=>$this->selectedStati]);
    }

    public function addToTest($id){
        //attach the given item to the test
        $this->test->items()->attach($id);
        dd($this->test->items);
    }

    public function removeFromTest($id){
        //detach the given item from the test
        $this->test->items()->detach($id);
        
    }

标签: laravelrenderlaravel-livewire

解决方案


将项目附加到测试集合刷新模型后,用新鲜数据重新水化它

public function addToTest($id){
   //attach the given item to the test
   $this->test->items()->attach($id);
   $this->test->refresh();
}

推荐阅读