我需要复制数据。但是我在应用程序上使用了2个数据库。但是,当我复制该数据时,我需要插入具有相同数据的新行。只有我不知道该怎么做。
我已经尝试了一些方法,所以我尝试复制该数据,然后再复制这些关系,但这对我没有用。因此,我问一个朋友,他说您需要在方法中使用插入。
public function copySurvey( Manager $fractal, SurveyTransformer $surveyTransformer ) {
// Copy function (Alleen nog niet volledig hier nog even aanwerken.)
$original = Survey::first();
$new = $original->replicate();
$new->sid = 123456;
$new->save();
foreach($original->groups as $group){
}
foreach($original->questions as $question){
$new->questions()->attach($question);
}
}
我的模特:
public function accuracy() {
return $this->hasOne( 'App\Models\LimeSurvey\Accuracy', 'survey_id', 'sid' );
}
public function groups() {
return $this->hasMany( 'App\Models\LimeSurvey\Group', 'sid', 'sid' )->orderBy('gid', 'asc')->orderBy('group_order', 'asc');
}
public function questions() {
return $this->hasMany( 'App\Models\LimeSurvey\Question', 'sid', 'sid' )->orderBy('gid', 'asc')->orderBy('question_order', 'asc');
}
public function parentQuestions() {
return $this->hasMany( 'App\Models\LimeSurvey\Question', 'sid', 'sid' )->where('parent_qid', '=', 0)->orderBy('gid', 'asc')->orderBy('question_order', 'asc');
}
public function languages() {
return $this->hasMany( 'App\Models\LimeSurvey\Language', 'surveyls_survey_id', 'sid' );
}
答案 0 :(得分:0)
您在模型中描述了两种类型的关系:
您需要复制相关的Accuray。这很容易,您只需要像进行调查一样复制模型即可。
$original = Survey::first();
// Firstly, clone the survey
$new = $original->replicate();
$new->sid = 123456;
$new->save(); // This is fine
// The clone the accuracy, and attach it to the cloned survey
$originalAccuracy = $original->accuracy;
$newAccuracy = $originalAccuracy->replicate();
$newAccuracy->survey_id = $new->sid;
$newAccuracy->save();
您需要一个一个地复制每个相关模型。我建议您执行以下操作:
$original = Survey::first();
$new = $original->replicate();
$new->sid = 123456;
$new->save(); // This is fine
/*
* Example for groups
* For each group related with the original survey, we create a clone group, and attach it to the new survey.
*/
$original->groups()->get()->each(function($originalGroup) use ($new) {
$newGroup = $originalGroup->replicate();
$newGroup->sid = $new->sid; // Adjust foreign key (in the related table) and local key (in survey table)
$newGroup->save();
});
编辑:您似乎不需要这部分,但如果可以帮助某人,我会允许的。
在复制模型时,除了多对多关系之外,所有关系都应该正常。
我怀疑问题与您对attach()
函数的使用有关。取自Laravel 5.8文档(https://laravel.com/docs/5.8/eloquent-relationships#many-to-many):
$user = App\User::find(1);
$user->roles()->attach($roleId);
如您所见,附加功能使用角色的ID 。
此外,在您的情况下,您想附加多个多对多模型。我将执行以下操作:
public function copySurvey( Manager $fractal, SurveyTransformer $surveyTransformer ) {
// Copy function (Alleen nog niet volledig hier nog even aanwerken.)
$original = Survey::first();
$new = $original->replicate();
$new->sid = 123456;
$new->save(); // This is fine
// Assuming groups() and questions() are BelongsToMany relationships
$new->groups()->attach($original->groups()->get()->pluck("id")->toArray());
$new->questions()->attach($original->questions()->get()->pluck("id")->toArray());
}