使用数组根据拥有的键查找所需值
// 不好的
$ceshi = 'epub';
if ($ceshi === 'pdf') {
$type = 'book';
} else if ($ceshi === 'epub') {
$type = 'book';
} else if ($ceshi === 'license') {
$type = 'license';
} else if ($ceshi === 'artwork') {
$type = 'creative';
} else if ($ceshi === 'song') {
$type = 'creative';
} else if ($ceshi === 'physical') {
$type = 'physical';
}
dd($type);
输出 : “book”
// 推荐的
$ceshi = 'epub';
$type = [
'pdf' => 'book',
'epub' => 'book',
'license' => 'license',
'artwork' => 'creative',
'song' => 'creative',
'physical' => 'physical',
][$ceshi];
dd($type);
输出 : “book”
使用短运算符
// 不好的
// truthy test
if (! $foo) {
$foo = 'bar';
}
// null test
if (is_null($foo)) {
$foo = 'bar';
}
// isset test
if (! isset($foo)) {
$foo = 'bar';
}
// 优雅的
// truthy test
$foo = $foo ?: 'bar';
// null test
$foo = $foo ?? 'bar';
// PHP 7.4
$foo ??= 'bar';
// isset test
$foo = $foo ?? 'bar';
// PHP 7.4
$foo ??= 'bar';
更新或创建
如果你需要检查记录是否存在,然后更新它,或者创建一个新记录,你可以用一句话来完成 - 使用 Eloquent updateOrCreate()
方法:
// 不要这样做
$flight = Flight::where('departure', 'Oakland')
->where('destination', 'San Diego')
->first();
if ($flight) {
$flight->update(['price' => 99, 'discounted' => 1]);
} else {
$flight = Flight::create([
'departure' => 'Oakland',
'destination' => 'San Diego',
'price' => 99,
'discounted' => 1
]);
}
// 一句话完成
$flight = Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99, 'discounted' => 1]
);
同时增减多个值
// 不好的
$user = User::query()->where('user_id', $user->user_id)->first();
$user->coin -= $ucb_number;
$user->quota += $dhj_number;
$user->quota_total += $dhj_number;
$user->save();
// 好的
User::query()->where('user_id', $user->user_id)
->update([
'coin' => \DB::raw('coin - ' . $total_fee),
'quota' => \DB::raw('quota + ' . $dhj_number),
'quota_total' => \DB::raw('quota_total + ' . $dhj_number),
]);