Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

relationship - Update records in intermediate(pivot) table in Laravel in a specific way

I have three table "questionaires", "questions" and "PivotQuestionaires". "questionaires" and "questions" are connected via foreign key through "PivotQuestionaires".

One questionaire *hasMany questions and question *belongsTo certain questionaire.

For example, if i have certain record in "PivotQuestionaires" which states: "Questionaire with id of 2 has questions with ids of 1,2 and 3 and if i want to change that to have only one specific question with for example with id 14. How would i do it?

Or if did it in different direction, if pivot has questionaire with only one question, but i want to update it with several?

What i'm trying to ask, questionaire should have ability to have variable number of questions. How to achieve such update? Is there a "Laravel" of doing this or should i devise specific logic for it?

Here is screenshot of schema to better visualize enter image description here Kudos in advance.

question from:https://stackoverflow.com/questions/65929413/update-records-in-intermediatepivot-table-in-laravel-in-a-specific-way

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Its a many to many relation between questionnaire and question like

class Questionnaire extends Model
{
    public function questions()
    {
        return $this->belongsToMany(Question::class, 'pivot_questionnaire', 'questionnaire _id', 'question_id');
    }
}
class Question extends Model
{
    public function questionnaires()
    {
        return $this->belongsToMany(Questionnaire::class, 'pivot_questionnaire', 'question_id','questionnaire_id');
    }
}

So if you want to assign multiple questions to questionnaire you can use attach & sync

$questionIds = [4,5];
$questionnaire->questions()->attach($questionIds);

this will add new associations [4,5] to existing ones like if previously if questionnaire has [1,2,3] then after attach() questionnaire will have [1,2,3,4,5]

$questionnaire->questions()->sync($questionIds);

If you use sync() it will removed all previous associations and add these new associations

Same goes for questions

$questionnaireIds = [4,5];
$question->questionnaires()->attach($questionnaireIds);
// OR
$question->questionnaires()->sync($questionnaireIds);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...