在编辑更新数据透视表上-laravel

时间:2018-09-08 06:41:35

标签: php laravel pivot-table

我有表questionstags和数据透视表question_tagquestion_tag表只有两个字段question_idtag_id

添加问题时,它还会在数据透视表中插入相应的值。

假设我更改表单中的问题标签并保存,它应该更新数据透视表值。如何更新数据透视表?我是laravel的新手。 我尝试过类似的

$question->tags()->updateExistingPivot($tag_id, array('any attribute'=>$value));

但就我而言,数据透视表中没有多余的属性

问题模型

public function tags()
    {
        return $this->belongsToMany('App\Tag');
    }

标记模型

public function questions()
{
    return $this->belongsToMany('App\Question');
}

3 个答案:

答案 0 :(得分:0)

尝试一下

$question->tags()->updateExistingPivot($question->id, ['tag_id' => $newTag->id]);

第一个值是您要匹配的值。如果要匹配问题,则应为问题ID。第二个参数是要更新的列,因此向其传递带有新标签的数组将起作用。我写了一个测试,效果很好。

/** @test */
public function it_can_update_the_pivot_table()
{
    // Create a Tag
    $tag      = factory(Tag::Class)->create();

    // Create a Question
    $question = factory(Question::Class)->create();

    // Create a pivot table record
    DB::table('question_tag')->insert(['question_id' => $question->id, 'tag_id' => $tag->id]);

    // Assert that there is a pivot table record before we attempt to change it
    $this->assertNotNull(DB::table('question_tag')->where([
        ['question_id', $question->id],
        ['tag_id', $tag->id],
    ]));

    // Attempt to change the with the tag id of the tag we created above.
    $question->tags()->updateExistingPivot($tag->id, ['tag_id' => 2]);

    // Query all pivot table records with the question id
    $new = DB::table('question_tag')->where(
        'question_id', $question->id
    )->first();

    // assert that the pivot record was updated
    $this->assertEquals(2, $new->tag_id);
}

答案 1 :(得分:0)

尝试一下:

$question->tags()->sync([$tag_id]);

答案 2 :(得分:0)

尝试一下

$question->pivot->attribute = "Value";

$question->pivot->save();