You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

是否混淆了integer数据类型?Laravel报int + App\Models\Rating操作数不支持如何解决

报错原因

unsupported operand types: int + App\Models\Rating报错属于类型不匹配错误,确实和整数类型用法混淆有关:
你在rate方法的两处round计算逻辑中,直接将Rating模型实例$rating与$this->ratings->sum('rating')返回的整数值做加法运算,PHP不支持直接对模型对象和整数执行算术运算,因此抛出该报错。
你观测到计算结果正常属于不可靠的偶发现象,不可作为正常逻辑依赖。

修复方法

将两处round计算中的+$rating替换为+$rating->rating,取模型对象的评分数值参与运算即可,同时建议同步更新$this->ratings集合,保证后续逻辑的计算准确性,修改后的对应代码如下:

已有评分更新分支逻辑

try {
    $rating->update();
    // 同步更新 ratings 集合
    $this->ratings = Rating::where('movie_id', $this->movie->id)->get();
    $this->currentRating = round($this->ratings->sum('rating') / $this->ratings->count(), 2) . ' / 5 (' . $this->ratings->count() . ' votes)';
} catch (\Throwable $th) {
    throw $th;
}

新增评分分支逻辑

try {
    $rating->save();
    // 同步更新 ratings 集合
    $this->ratings = Rating::where('movie_id', $this->movie->id)->get();
    $this->currentRating = round($this->ratings->sum('rating') / $this->ratings->count(), 2) . ' / 5 (' . $this->ratings->count() . ' votes)';
} catch (\Throwable $th) {
    throw $th;
}

内容的提问来源于stack exchange,提问作者Iman Mardhiah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 08:00:02