我正在嘗試向我的模型添加唯一驗證,但當我嘗試更新數據時出現錯誤。桌子:acq_m_budgets==================================budget_id serial NOT NULL,budget_code character varying(15) NOT NULL,budget_name character varying(100) NOT NULL,ma_code character varying(10),start_period timestamp without time zone NOT NULL,end_period timestamp without time zone NOT NULL,budget numeric(16) DEFAULT 0,credit numeric(16) DEFAULT 0,debet numeric(16) DEFAULT 0,balance numeric(16) DEFAULT 0,reserve numeric(16) DEFAULT 0,created_by character varying(100) NOT NULL,created_on timestamp without time zone DEFAULT now(),updated_by character varying(100) NOT NULL,updated_on timestamp without time zone DEFAULT now(),CONSTRAINT PK_AcqMBudgets PRIMARY KEY (budget_id),CONSTRAINT UN_AcqMBudgets UNIQUE (budget_code)我的模型:AcqMBudgets.phpclass AcqMBudgets extends Model{ public $timestamps = false; protected $primaryKey = 'budget_id'; public $sortable = ['budget_code', 'budget_name', 'ma_code', 'balance', 'updated_on']; protected $fillable = ['budget_code', 'budget_name', 'ma_code', 'start_period', 'end_period', 'budget', 'credit', 'debet', 'balance', 'reserve', 'created_by', 'created_on', 'updated_by', 'updated_on']; protected $attributes = [ 'budget' => 0, 'credit' => 0, 'debet' => 0, 'balance' => 0, 'reserve' => 0, ]; 在模型上,我已經將創建和更新方法的規則分開了。不同之處在于 updateRules() 中,規則數組中需要一個主鍵參數。在控制器的update功能上,出現錯誤,指出:SQLSTATE[42703]: Undefined column: 7 ERROR: column "id" does not exist LINE 1: ...from "acq_m_budgets" where "budget_code" = $1 and "id" <> $2 ^ (SQL: select count(*) as aggregate from "acq_m_budgets" where "budget_code" = N01 and "id" <> )。我使用的主鍵是整數和增量,但由于某些情況,主鍵的名稱不能只是id,所以我將其更改為budget_id并已在模型開頭聲明它。根據錯誤消息,Laravel 似乎一直在嘗試與該id字段而不是我聲明的字段進行比較。需要做什么來解決這個問題?
1 回答

MYYA
TA貢獻1868條經驗 獲得超4個贊
我將使用 Rule 命名空間,您可以通過它調用 unique。為此,您必須使用數組來驗證規則而不是字符串,無論如何,這是更好的可讀性方法。
Rule::unique
有第二個參數是 id 列的方法
'budget_code' => [
? ? 'required',
? ? Rule::unique('acq_m_budgets', 'budget_code')->ignore($id, 'budget_id'),
? ? 'max:15'
]
- 1 回答
- 0 關注
- 133 瀏覽
添加回答
舉報
0/150
提交
取消