我正在尝试使用laravel查询生成器求和JSON值+整数值,但无法进行类型转换错误,或者写查询时我做错了事。
Data saved in DB
comments: 100
fb_reactions: {"love":0,"like":8,"wow":0,"haha":0,"sad":0,"total":8,"angry":0}
$content = Content::select('id','social_id','comments','fb_reactions',DB::raw('SUM(fb_reactions->total+comments) as appreciation'))->groupBy('id');
应该给予赞赏= 108
答案 0 :(得分:0)
SUM
是一个数据库函数,通常可处理多个行数据,而不是同一行中的数据。最好不要在模型实例上进行简单添加,而要在数据库中进行简单添加。
向模型添加accessor:
// Content.php
protected $appends = ['appreciation']; // auto append to the model
protected $casts = ['fb_reactions' => 'array']; // auto cast json column to array
public function getAppreciationAttribute() {
return $this->comments + $this->fb_reactions['total'];
}