2017-08-06 58 views
0

我有一個這樣的陣列,它有它如何在Laravel中使用firstOrCreate將數組插入數據庫?

`array (size=120) 
    0 => 
    array (size=8) 
     'name' => That the quick brown fox jumps over the lazy - 7' (length=53) 
     'url' => string 'google.com/zyx' (length=134) 
     'category' => string 'search-engine' (length=6) 
    1 => 
    array (size=8) 
     'name' => string 'Mr. john brandy gave me a wall nut of quite' (length=67) 
     'url' => string 'yahoo.com/dzxser' (length=166) 
     'category' => string 'indian' (length=6)` 

我想將它們插入到我已經創建了模型,我的書籤表120元,我要確保複製不會發生。我發現這個https://laravel.com/docs/5.4/eloquent#other-creation-methods特別是firstOrCreate方法。

我假設我必須使用foreach,但我不知道如何。任何人都可以幫助我解決一些問題。

+0

在這裏沒有任何副本 –

+0

@AbdullaNilam我知道,但它是一個只有2個元素的例子。我告訴它總共包含120個元素,或者可能包含更多元素。 – coolsaint

+0

檢查這個http://laravel-tricks.com/tricks/using-eloquentfirstorcreate-to-prevent-duplicate-seeding和這個https://laracasts.com/discuss/channels/laravel/first-or-create-result –

回答

0

如果你不想在插入數組記錄時發生重複,那麼你所要做的就是設置一個約束,確保字段是唯一的。

如果您使用遷移創建DATABSE模式,你可以使用這樣的事情:$table->string('name')->unique();

現在爲例,這將確保「名稱」一欄的數據是

+0

我不想設置約束。我想使用firstorCreate方法。 – coolsaint

0

其實你不需要firstOrCreate,您需要updateOrCreate。檢查Laravel Other Creation methods您會發現該方法。

enter image description here

都說陣列處於$alldata

foreach($alldata as $data) { 
    MyModel::updateOrCreate($data); //the fields must be fillable in the model 
} 

這將運行更新/或120次的查詢而創建通過環路循環。好處是,你不能有重複,而如果有重複,它只能執行對錶的更新。

但是,確保數據以任何方式不重複的最佳方法是在創建數據庫表時進行設置。你可以在許多領域設置獨特的限制,如果這是你的情況。