复制更多表Laravel

时间:2019-05-21 08:44:54

标签: laravel

下一个问题是我必须复制几个表。现在我对Laravel并不那么熟悉,但是我已经尝试了一些东西。所以我的函数现在只复制了1个表。应当称为:

  • lime_groups
  • lime_permissions
  • Lime_questions等...

那么有人可以帮我吗?

public function copySurvey( Manager $fractal, SurveyTransformer $surveyTransformer ) {
        $copy = Survey::first();

        // copy all atributes
        $newsurvey = $copy->replicate();

        // save
        $newsurvey->save();
}

因此,我希望它会复制所选的内容。但是它仅复制该数据。它不会复制其他相关表

具有关系的模型:

 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' );

1 个答案:

答案 0 :(得分:0)

您必须手动执行

尝试以下代码:

public function copySurvey( Manager $fractal, SurveyTransformer $surveyTransformer ) {
    $copy = Survey::first();

    //copy attributes
    $newsurvey = $copy->replicate();

    foreach($copy->languages() as $language)
    {
        $newsurvey->languages()->attach($language);
    }

    foreach($copy->parentQuestions() as $question)
    {
        $newsurvey->parentQuestions()->attach($question);
    }

    foreach($copy->accuracy() as $acc)
    {
        $newsurvey->accuracy()->attach($acc);
    }

    foreach($copy->questions() as $question)
    {
        $newsurvey->questions()->attach($question);
    }

    foreach($copy->groups() as $group)
    {
        $newsurvey->groups()->attach($group);
    }

    // save
    $newsurvey->save();
}

这假设您的关系访问者是groups(), permissions(), questions()