假设我有一个表orders,其中包含字段id、userId、amount和description,还有一个表user,它有各种各样的字段。如果我想获取所有用户(及其所有字段)以及与该用户相关的订单的“amount”列的总和,该怎么办?
假设我有: user:{id:15,firstName:jim,lastName:morrison,gender:male}
order:{id:1,userId:15,amount:10,description:"order xxx"}, order:{id:3,userId:15,amount:40,description:"order yyy"}
我想要收到: user:{id:15,firstName:jim,lastName:morrison,gender:male,orderAmount:50}
当然,我想避免使用foreach语句。
我已在我的user模型上设置了这个。
假设我有: user:{id:15,firstName:jim,lastName:morrison,gender:male}
order:{id:1,userId:15,amount:10,description:"order xxx"}, order:{id:3,userId:15,amount:40,description:"order yyy"}
我想要收到: user:{id:15,firstName:jim,lastName:morrison,gender:male,orderAmount:50}
当然,我想避免使用foreach语句。
我已在我的user模型上设置了这个。
public function userOrder (){
return $this->hasMany('Order', 'userId');
}
我尝试过这个:
return $this->hasMany('Order', 'userId')->sum('amount');
一直都没有成功...