我在Laravel创建了一个工作,以获取设备的所有位置。当设备启动位置发送时,每次设备有新位置时,新记录将插入到具有最新位置的DB。
每当为同一设备发送新位置时,我想增加计数字段。除了COUNT列没有递增外,一切正常工作!!
这是我的职务代码
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Models\User;
use App\Models\Event;
use App\Models\Device;
use App\Models\Location;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
use App\Notifications\UpdatedMeta;
class SaveDataJob implements ShouldQueue
{
use InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* @return void
*/
private $request;
private $ip;
public function __construct($data)
{
$this->request = $data['request'];
$this->ip = $data['ip'];
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$request = $this->request;
// Try to identify the sender
$device= $this->identifyDevice($request['meta']);
// Fetch location data based on IP
$locationData = $this->getLocationData($this->ip);
$locationData['ip'] = $this->ip;
// If we matched the sender, check if a location with the same data exists already. Otherwise create a new location
if ($device) {
$locationData['locatable_id'] = $device->id;
$locationData['locatable_type'] = device::class;
$location = $this->findLocation($this->ip, $device, $locationData);
}
// the problem is here, I want to increment the count column when the device has new location
if (isset($location)){
$location->count++;
}
else {
$location = Location::create($locationData);
}
$location->save();
// Create and save events
$this->saveEvents($request['events'], $request['meta'], $device);
// Update device meta-data
if ($device) $updated = $device->updateMeta($request['meta']);
\Log::info("Handled data job");
}
private function identifyDevice($meta) {
$device= null;
// First try to identify with MAC address
if (array_has($meta, 'mac')) {
$device= Device::where('mac_wlan', $meta['mac'])->orWhere('mac_lan', $meta['mac'])->first();
}
// If not found, try to identify with device name
if (!$device&& array_has($meta, 'device_name')) {
$device= Device::where('device_name', $meta['device_name'])->first();
}
return $device;
}
private function getLocationData(String $ip) {
$client = new Client(); //GuzzleHttp\Client
$result = $client->get('http://ip-api.com/json/' . $this->ip);
return json_decode($result->getBody()->getContents(), true);
}
private function findLocation($ip, $device, $locationData) {
return Location::where('ip', $this->ip)
->where('locatable_id', $locationData['locatable_id'])
->where('locatable_type', $locationData['locatable_type'])
->first();
}
}
答案 0 :(得分:0)
尝试使用increment()
if ( $location ){
$location->increment('count');
$location->save():
}