首页 文章

在数据透视表中更改自己的ID

提问于
浏览
1

我正在开发一个Laravel应用程序,其中我有一个posts表,一个tags表和一个post_tag表作为数据透视表 .

现在我需要将帖子中的所有标签提供给另一个帖子 . 换句话说,我需要做:

$tags = $post->tags;

并将post_id更改为数据透视表中的每条记录 . 我已经设定了所有的关系 .

EDIT :这是我的代码

class Post extends Model
{
    public function tags()
    {
        return $this->belongsToMany(Tag::class)->withPivot('is_active')->withTimestamps();
    }

}

class Tag extends Model { }

主要问题是我必须保持is_active值不变 . 我只需要从数据透视表中替换post_id,其中post_id等于我要覆盖的那个(我知道我可以创建一个原始查询,但我试图避免它)

EDIT 2

我以这种方式工作,但我仍然喜欢面向对象的方式

DB::table('post_tag')->where('post_id', $post_a->id)->update(['post_id' => $post_b->id]);

2 回答

  • 0

    您可以使用lalovel文档中的Eloquent方法 updateExistingPivot

    如果需要更新数据透视表中的现有行,可以使用updateExistingPivot方法 . 此方法接受数据透视记录外键和要更新的属性数组:$ user = App \ User :: find(1);

    $ user-> roles() - > updateExistingPivot($ roleId,$ attributes);

  • 0

    尝试类似的东西

    $tags = $post->tags;
    
    //convert tags to IDs only for upcoming steps
    ... //an array of IDs
    
    $post->tags()->sync($tags); //remove the tags from this post
    $post2->tags()->sync($tags); // add the tags to this post
    

    这应该让你走到正确的轨道 .

    Update

    如果它只有一个,那就行了

    $post2->tags()->attach($tag, ['is_active' => true]);
    $post2->tags()->->sync([1 => ['is_active' => true], 2 => ['is_active' => true]);
    

    您可以尝试调整上面的示例 . 但我不知道如何使用一系列ID来完成它 .

相关问题