【问题标题】:Laravel, Anonymous Global scopes with joinsLaravel,带有连接的匿名全局范围
【发布时间】:2020-09-29 08:02:40
【问题描述】:

使用匿名全局范围。我收到一个错误。 这是我的代码,

protected static function boot(){
    parent::boot();
    $userId = 1;
    static::addGlobalScope('users', function (Builder $builder) use ($userId) {
     $builder->join("accounts_profiles_biz", 'users.id', '=', 'accounts_profiles_biz.user_id')->where('users.user_id', $userId);
    });
}

这里有错误

Exception Code: "SQLSTATE[42702]: Ambiguous column: 7 ERROR: column reference "id" is ambiguous LINE 1: ...s"."id" = "accounts_profiles_biz"."user_id" where "id" = $1 ... ^ (SQL: select * from "users" inner join "accounts_profiles_biz" on "users"."id" = "accounts_profiles_biz"."user_id" where "id" = 1 and "users"."deleted_at" is null and "users"."user_id" = 1 limit 1)"

【问题讨论】:

  • 请包括错误消息,还有一件事是全局范围被添加到每个查询中。我认为您应该使用本地范围。
  • 这个错误是针对插入操作的,不是针对范围或查询的,它必须在你代码的另一部分
  • @OMR 这里是错误异常代码:“SQLSTATE[42702]:不明确的列:7 错误:列引用“id”不明确第 1 行:...s"."id" = "accounts_profiles_biz "."user_id" where "id" = $1 ... ^ (SQL: select * from "users" inner join "accounts_profiles_biz" on "users"."id" = "accounts_profiles_biz"."user_id" where "id" = 1 并且 "users"."deleted_at" 为 null 并且 "users"."user_id" = 1 限制 1)"

标签: php laravel scope


【解决方案1】:

我认为问题出在这一行:

  $builder->join("accounts_profiles_biz", 'users.id', '=', 
'accounts_profiles_biz.user_id')->where('users.user_id', $userId);

users.user_id 列不存在,我认为..

应该是:

  $builder->join("accounts_profiles_biz", 'users.id', '=', 'accounts_profiles_biz.user_id')

->where('users.id', $userId);

【讨论】:

  • 否,出现同样的错误,异常代码:“SQLSTATE[42702]:不明确的列:7 错误:列引用“id”不明确第 1 行:...s"."id" = " accounts_profiles_biz"."user_id" where "id" = $1 ... ^ (SQL: select * from "users" inner join "accounts_profiles_biz" on "users"."id" = "accounts_profiles_biz"."user_id" where "id" = 1 和 "users"."deleted_at" 为空限制 1)"
  • 你能分享一下使用这个范围的代码吗?我的意思是使用它的查询?
  • 我正在使用匿名全球。受保护的静态函数 boot(){ parent::boot(); $userId = 1; static::addGlobalScope('users', function (Builder $builder) use ($userId) { $builder->join("accounts_profiles_biz", 'users.id', '=', 'accounts_profiles_biz.user_id')->where ('users.user_id', $userId); }); }
  • users表中是否有名为user_id的列?
  • 不,user_id 是该表“accounts_profiles_biz”中的一个列
猜你喜欢
  • 2015-07-06
  • 2021-01-15
  • 2016-11-16
  • 2016-04-14
  • 2021-11-10
  • 2015-12-02
  • 2016-11-11
  • 2012-05-03
相关资源
最近更新 更多