laravel 简洁之道

使用数组根据拥有的键查找所需值

		// 不好的
        $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),
    ]);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值