【发布时间】:2015-06-13 16:12:36
【问题描述】:
请对我温柔一点 - 我是 Laravel 菜鸟。
所以目前,我会遍历大量用户来决定是否需要更新相关模型 (UserLocation)。
如果需要创建一个UserLocation,我已经完成了,经过一番摸索,我想出了以下内容;
$coords = $json->features[0]->geometry->coordinates;
$location = new UserLocation(['lat'=>$coords[1],'lng'=>$coords[0]]);
$user->location()->save($location);
我的问题是第二次,位置可能需要更新,并且该用户已经存在一行。
这是自动处理的,还是我需要做一些不同的事情?
代码看起来像是在创建一个新行,所以不会处理需要更新它的情况吗?
更新 - 解决方案:
感谢 Matthew,我想出了以下解决方案;
$location = UserLocation::firstOrNew(['user_id'=>$user->id]);
$location->user_id = $user->id;
$location->lat = $coords[1];
$location->lng = $coords[0];
$location->save();
【问题讨论】: