Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/255.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel:创建或更新相关模型?_Php_Laravel_Models - Fatal编程技术网

Php Laravel:创建或更新相关模型?

Php Laravel:创建或更新相关模型?,php,laravel,models,Php,Laravel,Models,请对我温柔一点,我是一个拉拉威尔·努伯 因此,目前,我在大量用户中循环,决定是否需要更新相关模型(UserLocation) 如果需要的话,我已经创建了一个UserLocation,经过一番摸索,我得出了以下结论: $coords = $json->features[0]->geometry->coordinates; $location = new UserLocation(['lat'=>$coords[1],'lng'=>$coords[0]]); $

请对我温柔一点,我是一个拉拉威尔·努伯

因此,目前,我在大量用户中循环,决定是否需要更新相关模型(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();
你应该参考这本书。我认为他们在“常规文档”中没有提到这些方法,所以我理解为什么你可能没有看到它

您可以使用模型
firstOrNew
firstOrCreate
方法

firstOrNew:获取与属性匹配的第一条记录或实例化 它

firstOrCreate:获取与属性匹配的第一条记录或创建它

例如:

$model = SomeModel::firstOrNew(['model_id' => 4]);
在上面的示例中,如果找不到model_id为4的模型,那么它将创建
SomeModel
的新实例。然后可以对其进行操作,并在以后保存()。如果找到,则返回

您还可以使用
first或create
,它将立即将新模型插入表中,而不是创建新模型实例

所以在你的例子中:

$location = UserLocation::firstOrNew(['lat'=>$coords[1],'lng'=>$coords[0]]);
$location将包含数据库中的现有模型或属性
lat
lng
分别设置为
$coords[1]
$coords[0]
的新实例,您可以根据需要保存或设置更多属性值

另一个例子:

$location = UserLocation::firstOrCreate(['lat'=>$coords[1],'lng'=>$coords[0]]);

$location将包含数据库中的现有模型或重新设置属性的新模型,但这次如果找不到该模型,则该模型将已写入表中。

谢谢,这对找到我的解决方案有很大帮助-我已更新了OP。是,当我得知这件事时,这对我来说也是一个救命恩人:)很高兴能帮忙。