您可以使用自定义解决方案。
我正在解释一个示例,只是编码并且与您的问题非常相似,希望对您有所帮助。
我有一个 Question Model 和 AnswerOption Model,如下所示。
问题模型
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Question extends Model
{
protected $table = 'questions';
protected $fillable = [
'title',
'created_at',
'updated_at'
];
/**
* Get the answer options for the question.
*/
public function answerOptions()
{
return $this->hasMany('App\Models\AnswerOption');
}
/**
* @param array $answerOptions
*/
public function syncAnswerOptions(array $answerOptions)
{
$children = $this->answerOptions;
$answerOptions = collect($answerOptions);
$deleted_ids = $children->filter(
function ($child) use ($answerOptions) {
return empty(
$answerOptions->where('id', $child->id)->first()
);
}
)->map(function ($child) {
$id = $child->id;
$child->delete();
return $id;
}
);
$attachments = $answerOptions->filter(
function ($answerOption) {
// Old entry (you can add your custom code here)
return empty($answerOption['id']);
}
)->map(function ($answerOption) use ($deleted_ids) {
// New entry (you can add your custom code here)
$answerOption['id'] = $deleted_ids->pop();
return new AnswerOption($answerOption);
});
$this->answerOptions()->saveMany($attachments);
}
}
AnswerOption 模型
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class AnswerOption extends Model
{
protected $table = 'answer_options';
protected $fillable = [
'question_id',
'title',
'ord',
'created_at',
'updated_at'
];
/**
* Get the question that owns the answer.
*/
public function question()
{
return $this->belongsTo('App\Models\Question');
}
}
这里你可以看到一个问题有很多答案选项,你可以看到我在模型中使用了 BelongsTo , hasMany 关系。
现在在 QuestionController 中保存和更新问题时,您还可以保存答案选项。
为此,我在 Question Model 中编写了 syncAnswerOptions 方法。
你只需要传递带有 id 的选项数组,如果 id 已经存在于数据库中,那么它将更新,如果 id 为空,它将添加一条新记录,如果 Id 存在但不在你的新数组中,那么该记录将被删除。
/**
* If you are attaching AnswerOption(s) for the first time, then pass
* in just the array of attributes:
* [
* [
* // answer option attributes...
* ],
* [
* // answer option attributes...
* ],
* ]
*//**
* If you are attaching new AnswerOption(s) along with existing
* options, then you need to pass the `id` attribute as well.
* [
* [
* 'id' => 24
* ],
* [
* // new answer option attributes...
* ],
* ]
*/
在问题控制器的存储和更新方法中,在问题添加和更新调用之后调用此方法。
$question->syncAnswerOptions($data['answerOptions']);
$data['answerOptions'] 是答案选项数组,就像 cmets 中描述的那样。