【问题标题】:how to bind the model relation value in livewire wire:model?如何在 livewire wire:model 中绑定模型关系值?
【发布时间】:2021-10-01 13:00:28
【问题描述】:

有一个产品模型有很多描述关系。
descriptions 关系有两列,count,body。

我必须如何定义 wire:model 值才能在 Livewire 更新组件中显示选定的产品描述值?

我必须提到从关系中获取数据工作正常,只是无法在wire:model 属性的输入标签中显示数据!我认为问题出在受保护的$ruleswire:model 值的关键定义上!

更新类:

public $product;

protected $listeners = ['selectedProduct'];

public function selectedProduct($id){
    $this->product = Product::with('descriptions')->findOrFail($id);
}

protected $rules = [
    "description.count" => "required",
    "description.body" => "required",
];

livewire 视图:

@if($product)
    @foreach($product->descriptions as $description)
        <input type="text" wire:model="description.count">
        <texatarea wire:model="description.body"></texatarea>
    @endforeach
@endif

循环和字段数重复正确但没有数据显示!

【问题讨论】:

    标签: laravel laravel-livewire


    【解决方案1】:

    我想提几点,首先是您的视图应该始终只有 一个 根 HTML 元素 - 循环中生成的后续元素也应该有一个唯一的里面的根元素,上面有wire:keywire:key 在您的页面上应该是独一无二的。

    然后我们需要查看规则 - 任何模型都需要规则才能在输入元素中可见,这是正确的,但是您有一个元素集合,因此规则需要反映这一点。为此,您指定一个通配符作为键

    protected $rules = [
        "description.*.count" => "required",
        "description.*.body" => "required",
    ];
    

    然后必须将字段绑定到索引,以便 Livewire 知道它在集合中。

    <div>
        @if ($product)
            @foreach($product->descriptions as $index=>$description)
                <div wire:key="product-description-{{ $description->id }}">
                    <input type="text" wire:model="descriptions.{{ $index }}.count">
                    <texatarea wire:model="descriptions.{{ $index }}.body"></texatarea>
                </div>
            @endforeach
        @endif
    </div>
    

    最后,您需要将描述声明为类的公共属性,并将它们存储在那里。

    public  $product;
    public  $descriptions;
    
    protected $listeners = ['selectedProduct'];
    protected $rules = [
        "description.*.count" => "required",
        "description.*.body" => "required",
    ];
    
    public function selectedProduct($id){
        $this->product = Product::with('descriptions')->findOrFail($id);
        $this->descriptions = $this->product->descriptions;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-13
      • 2021-09-10
      • 2021-01-20
      • 2021-01-11
      • 2021-03-11
      • 2018-02-12
      • 1970-01-01
      • 2015-01-09
      • 1970-01-01
      相关资源
      最近更新 更多