值为null时在查询中使用if条件

时间:2019-05-17 04:26:11

标签: php laravel

在SQL查询中,我想添加if语句。如果数据库中的纬度和经度为null,则查询将运行并填充数据库中的值

$users = DB::table('users',IF ($user->lat && $user->lng == Null))->get();

foreach ($users as $user)
{
    $response = Geocode::make()->address($user->zipcode);

    if ($response) {
        $lat =   $response->latitude();
        $lng =  $response->longitude();
        $city =   $response->formattedAddress();
        echo  $response->locationType();

        DB::table('users')
            ->where('id', $user->id)
            ->update(['lat' => $lat,'lng' => $lng,'city' => $city]);

    }
}

2 个答案:

答案 0 :(得分:4)

$users = User::whereNull('lat')->whereNull('lng')->get();

foreach ($users as $user) {
    $response = Geocode::make()->address($user->zipcode);

    if ($response) {
        $lat = $response->latitude();
        $lng = $response->longitude();
        $city = $response->formattedAddress();
        echo  $response->locationType();

        $user->update(['lat' => $lat,'lng' => $lng,'city' => $city]);
    }
}

更多详细信息:

$city = $response->raw()->address_components[1]['long_name'];
$state = $response->raw()->address_components[2]['long_name'];
$country = $response->raw()->address_components[3]['long_name'];

答案 1 :(得分:1)

 DB::table('users')->where([
    ['users.lat', '=', NULL],
    ['users.lng', '=', NULL])->get();