2014-11-24 97 views
5

Tôi đã sử dụng sau chèn mảng để chèn nhiều mục trong LaravelEloquent ORMSử dụng updateOrCreate cho nhiều chèn dữ liệu trong Laravel

$i = 0; 
foreach($exerciseValArray as $kkey=>$exerciseValue){ 
    if($exerciseValue['exercise'] =='' || $exerciseValue['section_type'] == ''){ 
     return Response::JSON(array('errors'=>array('Error in workout exercise section'))); 
    } 
    $exerciseData = explode(',',$exerciseValue['exercise']); 
    foreach($exerciseData as $exerciseid){ 
     $insertArray[$i]['fk_workouts_id'] = $id; 
     $insertArray[$i]['fk_users_id'] = $userId; 
     $insertArray[$i]['fk_exercises_id']= $exerciseid; 
     $insertArray[$i]['section']  = $exerciseValue['section_type']; 
     $insertArray[$i]['status']   = 1; 
     $insertArray[$i]['item_index']  = $index+$kkey+1; 
     $insertArray[$i]['updated_at']  = $workoutDetails['updated_at']; 
     $i++; 
    } 
} 
WorkoutExercise::insert($insertArray); 

Đoạn mã trên hoạt động tốt và chèn mảng dữ liệu trong cơ sở dữ liệu .

Tôi đã học được cách sử dụng của Model::updateOrCreate và sử dụng nó trong một số module của tôi thành công (nghĩa là)

Model::updateOrCreate($attributes = array('key' => 'value'), $values = array('key' => 'value')); 

Câu hỏi của tôi là làm thế nào để chỉnh sửa đoạn chèn ở trên để tôi có thể sử dụng Model::updateOrCreate trong đó. Các trường $attributes của tôi là 'fk_workouts_id', 'fk_users_id', 'fk_exercises_id' và các trường còn lại trong số $values sẽ được thay đổi.

Tôi không biết cách triển khai điều này. Xin vui lòng giúp đỡ ...

+0

Eloquent không thể chèn/cập nhật nhiều hàng, bạn cần xử lý từng hàng một. Phương thức 'insert' trong thực tế là' Query \ Builder 'và nó không sử dụng các tính năng Eloquent (ví dụ: timestamps và vv). –

+0

là có cách nào khác trong 'Eloquent' hoặc' Query \ Builder' mà tôi có thể tạo mục nhập hoặc cập nhật nếu có sự hiện diện của dữ liệu @JarekTkaczyk.Bởi vì tôi cần phải cập nhậtOrCreate gần 20-50 dữ liệu là nó là một thực hành tốt để làm điều đó từng người một? – Ronser

+0

Thực hành tốt theo cách nào? Bạn có thể viết 3 dòng mã và để cho Eloquent thực hiện công việc, hoặc nói 13 dòng mã, nơi bạn thực hiện công việc. Eloquent có 'firstOrNew' phương pháp, đó là con đường để đi. –

Trả lời

6

Bạn có thể thử như thế nào,

Đầu tiên Way

$user = User::firstOrNew(array('name' => 'satish')); 
$user->field = 'value'; 
$user->save(); 

Nó sẽ kiểm tra cho người dùng name=satish nếu tìm thấy sau đó trả lại. Nếu không tìm thấy thì tạo mới và quay trở lại. Sau đó, bạn có thể đặt giá trị trường.

Kiểm tra liên kết này. http://laravel.com/docs/4.2/eloquent#insert-update-delete

Cách thứ hai Hồ sơ kiểm tra thủ công đang tồn tại.

$arr=array('field'=>"value"); 
$row = User::find($id); 
    if ($row === null) { 
     //Insert your record 

    } else { 
     //update your record 
    } 

CẬP NHẬT

Bạn cũng có thể sử dụng updateOrCreate - cập nhật một mô hình có sẵn hoặc tạo một mô hình mới nếu không tồn tại. updateOrCreate vẫn tồn tại mô hình, vì vậy không cần phải gọi save().

Example-

// If there's a flight from Oakland to San Diego, set the price to $99. 
// If no matching model exists, create one. 
$flight = App\Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'], 
    ['price' => 99] 
); 
1

Tôi nghĩ rằng bạn đang làm việc với khung tùy chỉnh của laravel vì vậy bạn có phương pháp UpdateOrCreate vì laravel không cung cấp phương pháp như vậy nếu giả định của tôi là đúng hơn so với mã dưới đây được viết có thể b hữu ích cho ứng dụng của bạn

foreach($exerciseValArray as $kkey=>$exerciseValue){ 

    if($exerciseValue['exercise'] =='' || $exerciseValue['section_type'] == ''){ 
    return Response::JSON(array('errors'=>array('Error in workout exercise section'))); 
    } 
    $exerciseData = explode(',',$exerciseValue['exercise']); 
    $attr_array = array('fk_workouts_id','fk_users_id','fk_exercises_id','section','status','item_index','updated_at'); 

    foreach($exerciseData as $exerciseid){ 

     $val_array = array($userId,$exerciseid,$exerciseValue['section_type'],1,$item_index,$workoutDetails['updated_at']); 
     WorkoutExercise::updateOrCreate($attr_array,$val_array); 
    } 
} 

Nhưng nếu bạn không sử dụng loại đó của khung tùy chỉnh hơn hãy thử với mã bên dưới nó có thể hoạt động tốt

foreach($exerciseValArray as $kkey=>$exerciseValue){ 

    if($exerciseValue['exercise'] =='' || $exerciseValue['section_type'] == ''){ 
    return Response::JSON(array('errors'=>array('Error in workout exercise section'))); 
    } 
    $exerciseData = explode(',',$exerciseValue['exercise']); 

    foreach($exerciseData as $exerciseid){ 

    $item_index = $index+$kkey+1; 

    // Retrieve the record by the fk_workouts_id, or create it if it doesn't exist... 
    $exercise = WorkoutExercise::firstOrCreate($attributes = array('fk_workouts_id' => $id)); 

    /* assign the values of other fields to store in database table*/ 
    $exercise->fk_users_id  = $userId; 
    $exercise->fk_exercises_id = $exerciseid; 
    $exercise->section   = $exerciseValue['section_type']; 
    $exercise->status   = 1; 
    $exercise->item_index  = $item_index; 
    $exercise->updated_at  = $workoutDetails['updated_at']; 
    $exercise->save(); // update the record 
    } 
} 

chúc may mắn ... :)

+0

các truy vấn sẽ được thực hiện trong suốt 'foreach' phải không ?? là có một cách để giảm thiểu các truy vấn? – Ronser

+0

Tôi không nghĩ vậy nên chúng tôi sẽ có giải pháp cho yêu cầu này. Nhưng nếu tôi thấy rằng sau đó chắc chắn sẽ trở lại với bạn .... – Neo

Các vấn đề liên quan