我在一个页面上显示数据和表单有问题。显示数据从数据库消失后写入文本区任何字。同样的问题列表,当我点击提交。在调试器中,只有第一个查询的数据,第二个查询被清除。我尝试用一个查询(秒),但它是相同的。
我的示例代码
-
路线网络:
Route::middleware(['auth:sanctum', 'verified'])->get('/tickets/show/{slug}', TicketsShow::class)->name('tickets.show');
Livewire:
public $ticket;
public $slug;
public $posts;
public $content_post;
public $ticket_id;
public function mount($slug){
$this->ticket = Tickets::where('tickets.id','=', $slug)->join('users', 'users.id', '=', 'tickets.user_id')
->select('users.email','users.phone','users.username','users.first_name','users.last_name','tickets.user_id','tickets.created_at',
'tickets.id', 'tickets.subject','tickets.status_id','tickets.admin_id')->first();
$this->posts = TicketsPost::where('tickets_posts.ticket_id','=', $slug)->join('users', 'users.id', '=', 'tickets_posts.user_id')
->select('users.email','users.username','users.first_name','users.last_name','tickets_posts.user_id','tickets_posts.created_at',
'tickets_posts.ticket_id','tickets_posts.post')->get();
}
public function addPost()
{
$this->validate([
'content_post' => 'required'
]);
$user_id = Auth::user()->getAuthIdentifier();
TicketsPost::create([
'ticket_id' => $this->ticket_id,
'user_id' => $user_id,
'post' => $this->content_post,
]);
}
public function render()
{
return view('livewire.tickets.show');
}
视图:
<p >#{{$ticket->id}}</p> <p >{{$ticket->subject}}</p> @foreach($posts as $post) <p >{{$post->first_name}} {{$post->last_name}}</p> <p >{{ date('d.m.Y H:i',strtotime($post->created_at)) }}</p> <p > {{$post->post}}</p> @endforeach <form > <input type="hidden" name="ticket_id" value="2" wire:model="ticket_id"> <textarea name="content_post" class="" rows="5" required="" placeholder="Treść wiadomości" wire:model="content_post"></textarea> @error('content_post') <span class="text-red-500">{{ $message }}</span>@enderror <button wire:click.prevent="addPost()" type="submit" class=""> <span id="btn_text" class="ml-2">Dodaj</span> </button> </form>
在Livewire中,确保你的组件只有一个单级根元素。并且,不要忘记在blade的每个循环中添加wire:key
元素。
你的循环应该像;
@foreach($posts as $key => $post)
<div wire:key="{{'post'.$key}}">
<p>{{$post->first_name}} {{$post->last_name}}</p>
<p >{{ date('d.m.Y H:i',strtotime($post->created_at)) }}</p>
<p > {{$post->post}}</p>
</div>
@endforeach