[英]How to add laravel query function lists in updateOrCreate eloquent
我試圖將updateOrCreate與多個條件一起使用,並且如果有相應的數據可用,則可以偶爾應用此條件。 我目前正在做的事情是先找到id是否存在,如果id存在,則更新,否則手動創建,但是現在我想使用laravel給定的updateOrCreate函數。
$existing = Student::where('name_last', $student['name_last'])
->where('name_first', $student['name_first'])
->where(function($query) use ($student) {
if (array_key_exists('phone_preferred', $student) && !empty($student['phone_preferred'])) {
$query->where('phone_preferred', $student['phone_preferred']);
}
if (array_key_exists('email_preferred', $student) && !empty($student['email_preferred'])) {
$query->where('email_preferred', $student['email_preferred']);
}
if (array_key_exists('home_street_address_1', $student) && !empty($student['home_street_address_1'])) {
$query->where('home_street_address_1', $student['home_street_address_1']);
}
if (array_key_exists('mailing_street_address_1', $student) && !empty($student['mailing_street_address_1'])) {
$query->where('mailing_street_address_1', $student['mailing_street_address_1']);
}
if (array_key_exists('mailing_address_city', $student) && !empty($student['mailing_address_city'])) {
$query->where('mailing_address_city', $student['mailing_address_city']);
}
})->first();
if($existing){
try{
Student::where('id', $existing->id)
->update($student);
} catch (\Exception $e) {
$error_encountered = true;
$error_arr[] = $e->getMessage();
$error_row_numbers[] = $row_no;
}
}
我想用類似的東西來實現:
try{
Student::updateOrCreate(
['name_first' => $student['name_first], 'name_last' => $student['name_last]],
$student
); //I could not get how to implement other occasional where condition
} catch (\Exception $e) {
$error_encountered = true;
$error_arr[] = $e->getMessage();
$error_row_numbers[] = $row_no;
}
我想包括那些偶爾在哪里查詢功能的updateOrCreate方法,目前正在手動方法中實現
您可以僅將要檢查的所有屬性添加到傳遞給updateOrCreate
的數組中
// these are your required conditions
$conditions = [
'name_first' => $student['name_first'],
'name_last' => $student['name_last'],
];
// these are optional
$attributes = [
'phone_preferred',
'email_preferred',
'home_street_address_1',
'mailing_street_address_1',
'mailing_address_city'
];
foreach($attributes as $attr){
// check to see if the attribute exists on the student
// and is not empty
if(isset($student[$attr]) && !empty($student[$attr])){
$conditions[$attr] = $student[$attr];
}
}
Student::updateOrCreate($conditions);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.