【问题标题】:laravel 4 updateExistingPivot with where clause not workinglaravel 4 updateExistingPivot with where 子句不起作用
【发布时间】:2015-05-24 01:03:18
【问题描述】:

我有两个模型:

用户资源

而关系表是resource_user

resource_user 中的字段是:

标识 |资源 ID |用户 ID |另一个_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() 函数不适用于我的表设置)..

【问题讨论】:

    标签: php laravel model eloquent relationship


    【解决方案1】:

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

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

    【讨论】:

    • @lukasgeiter,看来你可以帮助我。看看这个:stackoverflow.com/questions/44519339/…
    • 这似乎没有意义。将 'where' 子句与 'updateExistingPivot' 一起使用并不是很有用。因为“updateExistingPivot”不能一次更新多个 M:M 关系。它只能更新 id 是此方法的第一个参数的单个关系。 $resource_id = $this->resources()->wherePivot('another_id', 1)->first(); $this->resources()->updateExistingPivot($resource_id, array( 'value' => $value, 'updated_at' => new DateTime, ));
    猜你喜欢
    • 2018-01-21
    • 2013-06-30
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    • 2019-06-15
    • 2013-10-12
    • 1970-01-01
    • 2016-10-16
    相关资源
    最近更新 更多