我有一个简单的数据库查询,可以从数据库中输出一些内容,例如:
$user->HeadHits = DB::table('csstats AS cs')
->where('cs.steamid', '=', $user->steam_id)
->select("cs.h_1")
->first()->h_1;
和刀片:
@if ($user->HeadHits == 0)
0%
@else
<?php echo number_format($user->HeadHits / $user->AllHits * 100,2); ?>%
@endif
但如果在数据库中找不到用户steam\u id,我会出错:
试图获取非对象的属性
有什么建议吗?谢谢
最佳答案
这是因为当您使用DB
(查询生成器)和first
时,如果找不到行,它将返回null
。
您需要添加一个签入来查看该值是否存在:
$cs = DB::table('csstats AS cs')
->where('cs.steamid', '=', $user->steam_id)
->select("cs.h_1")
->first();
$user->HeadHits = $cs ? $cs->h_1 : 0;
较短的方法是使用value():
$user->HeadHits = DB::table('csstats AS cs')
->where('cs.steamid', '=', $user->steam_id)
->value('h_1') ?: 0;
最后,只需要一个FYI,但是不需要显式地在列名之前添加表别名,因为您只查询一个表。另外,您不需要将
=
与where()
相加,因为它将假定这是应该使用的运算符。最终,您可以将代码缩减为:$user->HeadHits = DB::table('csstats')->where('steamid', $user->steam_id)->value('h_1') ?: 0;