Hi
I'm working on a small application for a youth organisation. But I'm stuck in my mind ...
select kids.id, kids.cash, kids.forename, kids.surname, (kids.cash - SUM(IFNULL(sub.total, 0))) as money from ( select histories.kid_id, (COUNT(histories.item_id) * items.price) AS total from `histories` inner join `items` on `histories`.`item_id` = `items`.`id` group by `histories`.`kid_id`, `histories`.`item_id`, `items`.`price` ) AS sub right join `kids` on `sub`.`kid_id` = `kids`.`id` group by `kids`.`id`, `kids`.`forename`, `kids`.`surname`, `kids`.`cash` order by `kids`.`forename` asc, `kids`.`surname` asc
$kids = Kid::selectRaw('kids.id, kids.cash, kids.forename, kids.surname, (kids.cash - SUM(IFNULL(sub.total, 0))) as money')
->from(DB::raw(' ( ' . $subQuery->toSql() . ' ) AS sub '))
->mergeBindings($subQuery->getQuery())
->rightJoin('kids', 'sub.kid_id', '=', 'kids.id')
->groupBy('kids.id', 'kids.forename', 'kids.surname', 'kids.cash')
->orderBy('kids.forename')
->orderBy('kids.surname')
->get();
So the children's can put there money into the bank, and in the evening the can buy a drink and/or a snack. The selling will put a new record in the history table.
The query works fine, and the application does what it requires todo, but I would like to create a bulma/vue/api driven application instead of a jquery/bootstrap application. But the transformation isn't clear for me.
How can I put the query above into a resource/resource collection?
see my eloquent model for Kid
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Kid extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'forename',
'surname',
'cash',
];
protected $appends = [
'name',
'money',
];
private $money = 0;
public function name()
{
return sprintf('%s %s', $this->forename, $this->surname);
}
public function getNameAttribute()
{
return $this->name();
}
public function getMoneyAttribute($value)
{
if (empty($value) && empty($this->money)) {
return 0;
} else {
if (! empty($value) && empty($this->money)) {
$this->money = $value;
}
}
return $this->money;
}
public function histories()
{
return $this->hasMany(History::class);
}
}