我有一個問題,當我從其他 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');
}
uj5u.com熱心網友回復:
如果標題名稱是新的,您可以使用 first 或 create 將資料保存在資料庫中。使用 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:- 它試圖找到與您在第一個引數中傳遞的屬性匹配的模型。如果沒有找到模型,它會在應用第二個引數中傳遞的任何屬性后自動創建并保存一個新模型
uj5u.com熱心網友回復:
來自檔案
如果存在任何符合查詢約束的記錄,則可以使用
existsanddoesntExist方法
if($this->posts->where('title', $title)->doesntExist())
{
// save
} else {
// not save
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510080.html
標籤:php拉拉维尔雄辩
