多对多 – 在多个关系laravel4的情况下更新数据透视表

栏目: 编程语言 · PHP · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/15621279/update-pivot-table-in-case-of-many-to-many-relation-laravel4

我最近开始使用 Laravel 4.在多个关系的情况下,我在更新数据透视表数据时遇到一些问题.

情况是:

我有两个表:Product,ProductType.

它们之间的关系是多对多的.

我的模特是

class Product extends Eloquent {
    protected $table = 'products';
    protected $primaryKey = 'prd_id';

    public function tags() {
        return $this->belongsToMany('Tag', 'prd_tags', 'prta_prd_id', 'prta_tag_id');
    }
}

class Tag extends Eloquent {
    protected $table = 'tags';
    protected $primaryKey = 'tag_id';
        public function products()
    {
    return $this->belongsToMany('Product', 'prd_tags', 'prta_prd_id', 'prta_tag_id');
    }
}

在将数据插入数据透视表prd_tags时,我做了:

$product->tags()->attach($tag->tagID);

但是现在我想更新此数据透视表中的数据,将数据更新到数据透视表的最佳方法是什么.

比方说,我想删除一些标签并为特定产品添加新标签.

旧问题,但是在2013年11月13日,updateExistingPivot方法被公开用于多对多关系.这还没有在官方文档中.

public void updateExistingPivot(mixed $id, array $attributes, bool $touch)

– 更新表中的现有数据透视记录.

截至2014年2月21日,您必须包含所有三个参数.

在您的情况下,(如果您想更新数据透视字段’foo’),您可以:

$product->tags()->updateExistingPivot($tag->tagID, array('foo' => 'value'), false);

或者,如果要触摸父时间戳,可以将最后一个布尔值false更改为true.

拉请求:

https://github.com/laravel/framework/pull/2711/files

翻译自:https://stackoverflow.com/questions/15621279/update-pivot-table-in-case-of-many-to-many-relation-laravel4


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Ant Colony Optimization

Ant Colony Optimization

Marco Dorigo、Thomas Stützle / A Bradford Book / 2004-6-4 / USD 45.00

The complex social behaviors of ants have been much studied by science, and computer scientists are now finding that these behavior patterns can provide models for solving difficult combinatorial opti......一起来看看 《Ant Colony Optimization》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

在线进制转换器
在线进制转换器

各进制数互转换器

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具