【问题标题】:Get the missing objects from a ModelNotFoundException从 ModelNotFoundException 中获取丢失的对象
【发布时间】:2015-03-01 17:48:16
【问题描述】:

考虑以下场景:

User::findOrFail([1,2,5,6]);

假设数据库中不存在具有id = 5id = 6 的用户。所以会抛出ModelNotFoundException异常

有没有办法知道哪些是丢失的用户? 我想知道数据库中不存在的唯一用户是 5 和 6。

谢谢!

【问题讨论】:

  • 不是没有单独测试每个,除非它被抛出异常消息。在你的 catch 块中只是 $e->getMessage();

标签: php laravel eloquent laravel-5


【解决方案1】:

使用findOrFail 无法确定哪些未找到,因为该方法只是比较从数据库返回的项目数与您作为参数传递的 ID 数(它不关心哪些是 ID没有找到的地方)。当它抛出异常时,它只传递模型类名,仅此而已:

throw (new ModelNotFoundException)->setModel(get_class($this->model));

如果需要,您需要自己实现逻辑。这是一种方法:

$ids = [1, 2, 5, 6];

// Find the users
$users = User::find($ids)->get();

// Find the IDs that did not match
$notFoundIds = array_diff($ids, $users->modelKeys('id'));

if ( ! empty($notFoundIds))
{
    // throw your exception here
    // the missing IDs are in $notFoundIds
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    相关资源
    最近更新 更多