首页 > 解决方案 > Laravel - updateOrCreate or a sync method?

问题描述

I'm trying to see what my best route should be but for the sake of ease I will make this sound much simpler than it is.

I have two models, one called donor and one called donation. For the relationships, the donor has many donations.

In my edit form of the donor model, I have the ability to create, update or delete the donations from the same form.

Updating and creating are easy at the moment because I can use updateOrCreate. But what happens if I want to delete a donation?

Would I perform an actual query filtering out the ids of the donations that were still on the edit form (and therefore not deleted by the user) and then delete the models from there? Or is there a better way of handling this action?

Thanks in advance.

标签: laravellaravel-5

解决方案


在您的DonationController中,您可以使用如下查询选择要删除的捐赠:

public function destroy($id)
{

 $donation = Donation::where('donor_id','=', $id)->get();
 $donation->delete();

}

在您看来,您可以制作一个删除表单,然后他们将他发送到控制器中的此功能。我认为最好的方法是做一个 foreach 并循环内部捐赠者的捐款。

@foreach($donor->donations as $donation)
{
  <form method="POST" action="{{route('donor.destroy', $donation->id)}}">
  <button type="submit">Delete {{$donation->id}}</button>   
  </form>
}
@endforeach

推荐阅读