你还在为是否需要「判断数据库操作返回值」而烦恼吗?
结论要放最前面#
不用判断
前盐🧂#
查询构造器 和 Eloquent ORM 几乎是我们在 Laravel
中必用的数据库操作工具。
但很多时候我们在其使用方法上会产生疑问或歧义。
这是社区部分话题里存在的疑问:
这是官方文档上 ORM
相关方法的使用示例:
// save()
$flight = new Flight;
$flight->name = $request->name;
$flight->save();
// create()
$flight = Flight::create([
'name' => 'London to Paris',
]);
// update()
Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]);
但是文档上并没有说明是否需要对其返回值做判断。
至于为什么不用判断,先看下 Laravel
作者 Taylor Otwell 的解释,后面有更多案例!
解释#
这个 PR 还修改了 Model save () 的返回值
总结#
作者的回复已经很明确,这里要说明下特殊情况:
- 如果使用的是查询构造器的 update (), 其返回值是受影响的行数,可能为 0;
- 如果在模型事件(creating、saving、updating 等)中返回 false,save () 会取消操作并返回 false;
以上情况可以根据业务需要自行判断,对于第二种情况,作者在上面的 PR 里其实也有回复
另外,很多人说用
try catch
,为什么要手动处理?项目里没有异常处理机制?
案例(大量截图)#
Laravel 官方项目#
Laravel Breeze#
breeze/NewPasswordController.php · laravel/breeze (github.com)
breeze/PasswordController.php · laravel/breeze (github.com)
Laravel Cashier#
cashier-stripe/ManagesCustomer.php · laravel/cashier-stripe (github.com)
cashier-stripe/Subscription.php · laravel/cashier-stripe (github.com)
Laravel Jetstream#
jetstream/CreateNewUserWithTeams.php · laravel/jetstream (github.com)
jetstream/Team.php · laravel/jetstream (github.com)
Laravel Sanctum#
sanctum/HasApiTokens.php · laravel/sanctum (github.com)
sanctum/Guard.php · laravel/sanctum (github.com)
Laravel Telescope#
telescope/DatabaseEntriesRepository.php · laravel/telescope (github.com)
非官方 Laravel 系项目#
Flarum(论坛)#
framework/ValidatePost.php · flarum/framework (github.com)
framework/OrderTagsController.php · flarum/framework (github.com)
Deployer(应用程序部署系统)#
deployer/ProfileController.php · REBELinBLUE/deployer (github.com)
deployer/EloquentUserRepository.php · REBELinBLUE/deployer (github.com)
推荐文章: