【问题标题】:On edit update pivot table - laravel在编辑更新数据透视表 - laravel
【发布时间】:2018-09-08 06:41:34
【问题描述】:

我有表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');
}

【问题讨论】:

  • 所以您只是希望能够在问题中添加或删除标签?您是否为此设置了表单和控制器方法?

标签: php laravel pivot-table


【解决方案1】:

试试这个

$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);
}

【讨论】:

  • 我认为答案应该是$tag_id 而不是$question->id
  • @rkj 这真的取决于。如果他想通过问题 id 获取 question_tag 表中的所有记录,则需要 $question->id。如果他需要通过标签 id 查询,那么$tag_id 将起作用。
【解决方案2】:

试试这个:

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

【讨论】:

    【解决方案3】:

    试试这个

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

    $question->pivot->save();

    【讨论】:

      猜你喜欢
      • 2021-09-24
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 2016-03-09
      • 1970-01-01
      • 1970-01-01
      • 2017-07-01
      • 1970-01-01
      相关资源
      最近更新 更多