gpt4 book ai didi

php - 奇怪的 Laravel 错误(从范围加入)错误的 ID 列

转载 作者:可可西里 更新时间:2023-11-01 07:39:28 25 4
gpt4 key购买 nike

这是错误输出

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is 
ambiguous
(SQL: update `table1` inner join `table2` on
`table1`.`type_id` = `table2`.`id` set `type_id` = 2,
`updated_at` = 2015-01-09 19:36:16
where `table1`.`site_id` = 1 and `id` = 1)

在本文中,我只是为了提出这个问题而编辑了表名。所讨论的查询是设置表中项目的“类型”,table1 具有 id,它与 table2 的类型定义(名称、描述等)相关。

这是原始错误输出,但是最后有一个错误的 ID,它应该是 table1.id 而不仅仅是 id。不仅如此,加入甚至不应该在更新中。

通常这将是一个快速而简单的修复,但它完全是 Eloquent。唯一奇怪的部分是我正在使用一个范围来应用连接,我相信这就是造成这种情况的原因,但是通过挖掘文档我还没有找到修复它的方法。

我的范围适用于以下内容:

public function apply(Builder $builder)
{
$builder->join('table2', 'table1.type_id', '=', 'table2.id');
}

我在想我需要用某种 if 语句将它包装起来,但文档是死胡同,没有一个示例使用这样的东西。

有人知道解决这个问题的方法吗?将深入研究源代码,但这总是一种沉闷的体验。

编辑:这里或多或少来自 Eloquent 的查询

$model = Model::find($id); 
$model->type_id = 2;
$model->save();

编辑:

一个有前途的想法是手动将模型的主键设置为 table1.id,但是这样做会导致它改为使用 table1.table1.id。看到我试图只设置 id 但它又回到了最初的问题,即不添加 table1

最佳答案

在你的模型上覆盖这些:

// if you have timestamps on both tables
const UPDATED_AT = 'table1.updated_at';
const CREATED_AT = 'table1.created_at';

protected function setKeysForSaveQuery(\Illuminate\Database\Eloquent\Builder $query)
{
$query->where($this->getQualifiedKeyName(), '=', $this->getKeyForSaveQuery());

return $query;
}

你会好起来的!

关于php - 奇怪的 Laravel 错误(从范围加入)错误的 ID 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27868375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com