【问题标题】:Laravel API - Trying to forbid admins to delete a product if the product is orderedLaravel API - 如果订购了产品,试图禁止管理员删除产品
【发布时间】:2021-08-01 18:47:56
【问题描述】:

正如标题所说,我正在尝试确定该产品是否未订购,否则管理员可以删除该产品。它似乎有效,但我认为我没有以正确的方式处理它,因为控制台返回错误 500。

这是我在 ProductController中的销毁函数:

public function destroy(Product $product)
{
    $ordersLink = $product->orders()->where('orders.product_id', $product->id)->exists();

    if(!$ordersLink) {
        $status = $product->delete();
    } 

    return response()->json([
        'status' => $status,
        'message' => $status ? 'Product removed' : 'Product not removed'
    ]); 
}

当产品无法删除时会抛出错误,但它应该返回“产品未删除”。

任何帮助将不胜感激!干杯

【问题讨论】:

  • 订单id和商品id一样吗?
  • 哦等等!你说得对,我是瞎子。我纠正了它,但它仍然给我同样的错误。
  • 当您调用 $product->orders() 时,如果您正确定义了关系,它已经在寻找具有该产品 ID 的订单。当没有订单时,它不能转到下一个查询->where('orders.product_id', $product->id)。您应该检查订单是否存在,下一部分导致错误
  • 如果您想自己查看订单,那么您应该更改 $product->orders()->where('orders.product_id', $product->id)->exists();类似于 Order::where('orders.product_id', $product->id)->exists();

标签: laravel api controller laravel-8 laravel-api


【解决方案1】:

以下代码替换:

public function destroy(Product $product)
{
    $status = false;
    $ordersLink = $product->orders()->exists();

    if(!$ordersLink) {
        $status = $product->delete();
    } 

    return response()->json([
        'status' => $status,
        'message' => $status ? 'Product removed' : 'Product not removed'
    ]); 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多