Yii2报错:调用int类型的andWhere()成员函数问题排查
Yii2错误:Call to a member function andWhere() on int 排查与解决
错误原因
Item::updateAll() 是Yii2中直接执行更新操作的方法,返回值是受影响的行数(整数类型),而非ActiveQuery查询对象。你在调用updateAll()后链式调用andWhere(),相当于在一个整数上调用对象方法,因此触发该错误。
解决办法
要实现“更新指定organization_id下所有Item的is_rtm_enable字段为0”的需求,需将查询条件作为updateAll()的第二个参数传入,而非链式调用andWhere():
public function actionItemsenbale($organization_id) { $affectedRows = Item::updateAll( ['is_rtm_enable' => SharedConstant::VALUE_ZERO], ['organization_id' => $organization_id] ); return (new ApiResponse)->success(['affected_rows' => $affectedRows]); }
扩展写法(复杂条件场景)
如果需要更复杂的查询条件,可先构建ActiveQuery对象再调用update()方法:
public function actionItemsenbale($organization_id) { $affectedRows = Item::find() ->where(['organization_id' => $organization_id]) ->andWhere(['status' => 1]) // 额外筛选条件 ->update(['is_rtm_enable' => SharedConstant::VALUE_ZERO]); return (new ApiResponse)->success(['affected_rows' => $affectedRows]); }
内容的提问来源于stack exchange,提问作者saqib afridi
相关产品推荐
相关产品推荐

