如何在前端Livewire中实现复杂的多模型CRUD

问题描述 投票:0回答:1

我想在 laravel livewire 中添加一个帖子,如果类别不在下拉列表中,那么它应该创建一个具有该名称的类别,类似地,对于我刚开始使用 livewire 的标签,请帮助我如何在没有页面的情况下实现这一目标最终提交时加载。

我已经尝试过了

function mount(){
$this->categories= Categories::all();
$this->category = $this->article->category;
$this->post_tags = $this->article->tags;
$this->tags = Tags::all();
-------
--------
--------
}

function store(){
    $this->article->description = $this->description;
----
----
----
}

但是在更改表单时,我没有通过“$this->category”和“$this->post_tags”将类别和标签放入存储方法中。这仅返回 null 或在编辑数据库中的旧值而不是表单值时

laravel laravel-livewire laravel-10 livewire-3
1个回答
0
投票

要获取 livewire 中的下拉值,您需要更改选择以包含

wire:model
并在类上添加公共属性

接下来,你可以使用 Laravel Collections 方法

::contains
来查看该类别是否存在,如果不存在则创建。

应该看起来像这样:

new class extends Component
{
    public ?Collection $categories = null;
    public string $category = '';
    ...

    public function mount() {
        $this->categories = Categories::all();
    }

    public function store() {
        if (!$this->categories::contains($this->category)) {
            // Category does not exist, create
            ...
        }
    }
}
...
<div>
    <select id="category" wire:model="category"...>
        ...
    </select>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.