【问题标题】:Eloquent global scope interfering with Delete requests雄辩的全局范围干扰删除请求
【发布时间】:2016-12-07 10:23:40
【问题描述】:

我有这个全局范围:

class EarmarkScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->leftJoin('users', 'users.id', '=', 'earmarks.by_id')
            ->leftJoin('locations', 'locations.id', '=', 'earmarks.location_id')
            ->select('earmarks.*', 'users.name AS by', 'locations.location')
            ->orderBy('date', 'ASC');
    }
}

但是当试图打电话时:Earmark::destroy($id); 我得到这个错误:

SQLSTATE[23000]:违反完整性约束:1052 列 'id' 在 where 子句不明确 (SQL: select earmarks.*, users.name as by, locations.location from earmarks left join users on users.id = earmarks.by_id 左加入locations on locations.id = earmarks.location_id 其中id 按 (72) 顺序 dateasc)

我意识到全局范围是造成这种情况的原因,但是拥有该范围可以为我节省很多时间在 SELECT 查询上。如何避免它导致 destroy() 和其他有用的 Laravel 函数(如 find())出现问题?

【问题讨论】:

  • 如果你使用Earmark::withoutGlobalScope(EarmarkScope::class)->destroy($id)会发生什么?
  • 我收到Call to undefined method Illuminate\Database\Query\Builder::destroy()
  • 如果您不介意,您使用的是哪个 laravel 版本?无论如何,just read the code 它没有应用范围来破坏东西..
  • 我使用的是 Laravel 5.3
  • 很奇怪,模型在删除时根本不应该触发任何范围,source。你是怎么调用查询的,是不是只有Earmark::destroy($id);..?或者,你能做到Earmark::withoutGlobalScope(EarmarkScope::class)->find($i‌​d)->delete() 吗?

标签: laravel eloquent


【解决方案1】:

你在这里做错了。

A.在模型上设置关系。这里绝对不需要全局范围。

B.不要在全局范围内使用joins,而是使用whereIn

$builder->whereIn(
    'by_id', function ($q) {
    $q->select('users.id')
        ->from('users')
        ->where('something useful...');

}
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-21
    • 2012-04-23
    • 2014-08-14
    • 2018-10-22
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2020-12-14
    相关资源
    最近更新 更多