php - 带有where子句的laravel 4 updateExistingPivot不起作用

标签 php laravel model eloquent relationship

我有两个模型:

用户资源

关系表是resource_user

resource_user 中的字段是:

id | resource_id | user_id | another_id

我在用户中有这种关系:

public function resources() {
        return $this->belongsToMany('Resource')->withPivot(array(
            'value',
            'another_id',
        ));
    }

现在我想更新我的数据透视表:

(在模型用户中有这个代码示例)

$this->resources()->whereAnotherId(1)->updateExistingPivot($resource_id, array(
                            'value' => $value,
                            'updated_at' => new DateTime,
                        ));

问题是 another_id。

如果我的关系表中有两个条目 (resource_user) 但有不同 another_id 的。在此示例中,laravel 将更新两个条目。但这不是我想要的。 在此示例中,仅应更新一个条目(another_id = 1 的条目)。 这是一个错误,还是我如何更新我的数据透视表(sync() 函数不适用于我在此处设置的表)。

最佳答案

尝试使用 wherePivot() 代替。使用 whereAnotherId(1) 您的目标是 Resource 表而不是数据透视表...

$this->resources()->wherePivot('another_id', 1)
                  ->updateExistingPivot($resource_id, array(
                        'value' => $value,
                        'updated_at' => new DateTime,
                    ));

关于php - 带有where子句的laravel 4 updateExistingPivot不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29169606/

相关文章:

php - Laravel 4 Ajax 检查以包含 XMLHttpRequest(来自 Magnific Popup)

ruby-on-rails - 模型外键验证

php - 如何限制此 PHP 代码抓取与给定域具有相同基础的链接?

php - Azure AD 组配置 : not getting PATCH request from AD when updating the group

php - 复杂的 SQL 查询... 3 个表,需要最近 24 小时内最流行的使用时间戳

php - 在 Laravel 中手动注册用户

git - 从 git 存储库使用 Composer 安装包

php - 如何将数据发送到具有相同用户ID作为主键的两个表?

c# - 如何在Orchard中创建表关系?

python - Django 。将模型方法保存到不同的模型