我有一个问题,当我从其他api获得数据时,如果同一个标题不能保存到api中,我想要这样做。每次从api中获取数据是20次,并且希望将其保存到数据库中,而不需要重复。请帮帮我。非常感谢!
public function getTitle($title){
$title = $this->posts->where('title', $title)->get();
return $title;
}
public function getApi(Request $request){
$url = "https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=87384f1c2fe94e11a76b2f6ff11b337f";
$data = Http::get($url);
$item = json_decode($data->body());
$i = collect($item->articles);
$limit = $i->take(20); // take limited 5 items
$decode = json_decode($limit);
foreach($decode as $post){
$ite = (array)$post;
$hi = $this->getTitle($ite['title']);
dd($ite['title'], $hi);
if($ite['title']==$hi){
dd('not save');
}
else{
dd('save');
}
//dd($hi, $ite['title']);
// create post
$dataPost = [
'title'=>$ite['title'],
'description'=>$ite['description'],
'content'=>$ite['content'],
'topic_id'=>'1',
'post_type'=>$request->type,
'user_id'=>'1',
'enable'=>'1',
'feature_image_path'=>$ite['urlToImage']
];
//dd($dataPost);
//$this->posts->create($dataPost);
}
return redirect()->route('posts.index');
}发布于 2022-09-29 07:13:18
如果标题名称是新的,则可以先使用或创建用于在数据库中保存数据。使用firstOrNew,您不必使用任何其他条件,例如:-
$this->posts->firstOrCreate(
['title' => $ite['title']],
['description'=>$ite['description'],
'content'=>$ite['content'],
'topic_id'=>'1',
'post_type'=>$request->type,
'user_id'=>'1',
'enable'=>'1',
'feature_image_path'=>$ite['urlToImage']]);firstOrNew:-它试图找到一个与您在第一个参数中传递的属性相匹配的模型。如果找不到模型,则在应用第二个参数中传递的任何属性之后,它会自动创建和保存一个新模型
发布于 2022-09-29 06:36:29
来自文档
如果存在与查询约束匹配的任何记录,则可以使用
exists和doesntExist方法
if($this->posts->where('title', $title)->doesntExist())
{
// save
} else {
// not save
}https://stackoverflow.com/questions/73891118
复制相似问题