2015-10-19 26 views
2

比方說,我有一個下表:id |名稱|電子郵件| create_date | creator_idLaravel first或創建例外

當我使用Laravel的firstOrCreate方法時,它會複製我的記錄,因爲每次調用create_date和creator_id參數都會被更改。有沒有辦法在檢查數據庫中已有的記錄時忽略這些字段?

僞例子可能是這樣的:firstOrCreate(array('name'=>'test', 'email'=>'[email protected]'), $exceptionsArray('create_date', 'creator_id'))

回答

3

firstOrCreate()方法接受一組屬性,並且它基於來自那些返回或創建記錄的屬性的記錄的存在。

例如:

| id | name | created_at   | 
| 1 | Joe | 2015-10-01 01:00:00 | 
| 2 | Sam | 2015-10-01 01:00:00 | 
| 3 | Ali | 2015-10-01 01:00:00 | 
| 4 | Tom | 2015-10-01 01:00:00 | 

$user = User::firstOrCreate(['name' => 'Joe']); 

// $user = record with id 1 

這是現有的用戶,因爲firstOrFail()執行:

User::where('name', 'Joe')->first(); 

下一頁例如:

$user = User::firstOrCreate(['name' => 'Joe', 'created_at' => '2015-10-01 01:00:00']); 

// $user = record with id 1 

這使用戶返回,因爲罩下的執行以下查詢:

User::where('name', 'Joe')->where('created_at', '2015-10-01 01:00:00')->first(); 

$user = User::firstOrCreate(['name' => 'Joe', 'created_at' => '2020-10-01 01:00:00']); 

// $user = a brand new user, as the created_at time is different 

firstOrCreate()方法所做的是檢查記錄是否存在您傳遞給它的屬性。

所以,取最後一個例子,它之所以創造了一個新紀錄,是因爲它評價:

User::where('name', 'Joe')->where('created_at', '2020-10-01 01:00:00')->first(); 

這當然會失敗。

總之,使用firstOrCreate時,沒有傳遞created_at屬性,因爲始終是動態創建的,在很多情況下,你可能不希望包括creator_id

+0

謝謝,它是有道理的 –

1

我不知道這是一個選擇,但你可以只使用存在()方法您的查詢是這樣的:

if (Model::where('name', '=', 'test')->where('email', '=', '[email protected]')->exists()) { 
    // do something 
} else { 
    // add new record 
}