laravel Livewire在装载时生成集合,但在刷新时生成阵列

ntjbwcob  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(112)

我有一个(相对)简单的Livewire控制器,它在mount()上生成一个游戏集合,按开始日期分组,并将其分配给$games公共属性。

public $games;
protected $rules = [];
...
public function mount() {
    $now = Carbon::now();
    $games = Game::where('start', '>', $now)->orderBy('start', 'ASC')->get();
    $games = $games->groupBy(function($item) {
        return $item->start->format("Y-m-d H:i:s");
    })->collect();
    $this->games = $games;
}

然后,相应的组件循环遍历日期,输出日期,然后将游戏本身发送到Blade组件(删除了不相关的样式):

@foreach($games as $date => $thegames)
    <div>
        {{ \Carbon\Carbon::createFromFormat("Y-m-d H:i:s", $date)->format("l jS \of F Y - g:i A") }}
    </div>
    <div>
        <x-individual.game :allgames="$thegames" :user="Auth::user()"></x-individual.game>
    </div>
@endforeach

然后Blade组件循环遍历给定的游戏并渲染每个游戏(简化如下):

@foreach($allgames as $game)
    <div>
        <div>
            <h3>
            {{ $game->game->name }}
            </h3>
        </div>
    </div>
@endforeach

在该组件(未显示)中有wire:click按钮,它可以向游戏中添加一个人,也可以删除一个人。这又触发了原始Livewire组件的refresh()函数,该函数与mount()函数相同,保存它在最后发出refreshComponent事件:

public function refreshThis() {
    $now = Carbon::now();
    $games = Game::where('start', '>', $now)->get();
    $games = $games->groupBy(function($item) {
        return $item->start->format("Y-m-d");
    })->collect();
    $this->games = $games;
    $this->emit('refreshComponent');
}

这就是问题的根源。它没有像它应该的那样重新呈现组件,而是在刀片组件中生成“Attempt to read property“game”on array”的错误:

{{ $game->game->name }}

当然,此时$game现在是一个数组,而不是Eloquent对象(或第一次出现时任何对象)。
如果我手动刷新页面,更改会显示出来,没有问题。但是为什么它在刷新时向我发出一个数组,(更重要的是)我该如何停止它?

svmlkihl

svmlkihl1#

您可以将$games添加到render方法中,它将refresh数据:

public function render()
{
    $now = Carbon::now();
    $games = Game::where('start', '>', $now)->orderBy('start', 'ASC')->get();
    $games = $games->groupBy(function($item) {
        return $item->start->format("Y-m-d H:i:s");
    })->collect();

    return view('livewire.your_component_view', [
        'games' => $games
    ]);
}

然后刷新组件(在主组件中):

public function refreshThis() {
    $this->render();
}

如果从子组件调用刷新,则可以在此处调用它:子组件:

$this->emit('refreshThis');

相关问题