Laravel 4.2:如何按优先级条件保存数据?
Hey there! Let's work through how to handle priority-based data saving in Laravel 4.2 based on your specific requirements.
First, let's recap the rules you've laid out:
- If
input 1equals1, set the priority tolastwhen saving - If
input 2equals0, set the priority tofirstwhen saving
A quick note upfront: what if both conditions are true at the same time? We'll need to define a precedence order for this example, so I'll assume we check the input 1 condition first — if it's met, we use last, otherwise we check input 2 for first. We'll also add a default priority for cases where neither condition applies.
1. Retrieve Input Values
In your controller's store/update method, grab the input values using Laravel's Input facade:
$input1 = Input::get('input1'); $input2 = Input::get('input2');
2. Determine the Priority
Apply your conditional logic to set the correct priority value:
// Set a default priority for fallback $priority = 'normal'; // Check input1 first (higher precedence) if ($input1 == 1) { $priority = 'last'; } // Check input2 only if input1 condition isn't met elseif ($input2 == 0) { $priority = 'first'; }
If you want input 2 to take precedence over input 1 (adjust based on your actual needs), just reverse the order of checks:
$priority = 'normal'; if ($input2 == 0) { $priority = 'first'; } elseif ($input1 == 1) { $priority = 'last'; }
3. Save the Data with Priority
Now create or update your model with the calculated priority. Let's use a hypothetical Task model (swap this with your actual model name):
Creating a new record:
$task = new Task; $task->input1 = $input1; $task->input2 = $input2; $task->priority = $priority; $task->save();
Updating an existing record:
$task = Task::find($id); $task->fill([ 'input1' => $input1, 'input2' => $input2, 'priority' => $priority ])->save();
If you want to keep your controller code clean and encapsulate the priority logic within your model, use a saving observer. This way, the priority is automatically calculated every time the model is saved.
In your Task model:
protected $fillable = ['input1', 'input2', 'priority']; // Ensure these are fillable public static function boot() { parent::boot(); // Automatically set priority before saving static::saving(function($model) { $priority = 'normal'; if ($model->input1 == 1) { $model->priority = 'last'; } elseif ($model->input2 == 0) { $model->priority = 'first'; } else { $model->priority = $priority; } return true; // Allow the save operation to proceed }); }
Now your controller code becomes much simpler:
// Create a new record $task = Task::create(Input::all()); // Or update an existing record $task = Task::find($id); $task->fill(Input::all())->save();
内容的提问来源于stack exchange,提问作者Kent

