Reputation: 19
How to convert from native php into query builder laravel
$statsMoneyInPlay = array();
$sql_query = "SELECT UNIX_TIMESTAMP(Date(ts))*1000 As ts, sum(pot + p1pot + p2pot + p3pot + p4pot + p5pot + p6pot + p7pot + p8pot + p9pot) / count(*) As moneyInPlay FROM enginepoker_log.poker WHERE GROUP BY Date(ts) ORDER BY Date(ts) LIMIT 30 ";
and I already make query builder but still got an error. and this is the error
(2/2) QueryException SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT UNIX_TIMESTAMP(Date(ts)*100 as ts), sum(pot + p1pot + p2pot + p3pot + p4p' at line 1 (SQL: select SELECT UNIX_TIMESTAMP(Date(ts)100 as ts), sum(pot + p1pot + p2pot + p3pot + p4pot + p5pot + p6pot + p7pot + p8pot + p9pot) / count() As moneyInPlay from
enginepoker_log
.poker
group byDate(ts)
order byDate(ts)
asc)
this is query builder:
$statsMoneyInPlay = DB::table('enginepoker_log.poker')
->selectRaw("SELECT UNIX_TIMESTAMP(Date(ts)*100 as ts)")
->selectRaw("sum(pot + p1pot + p2pot + p3pot + p4pot + p5pot + p6pot + p7pot + p8pot + p9pot) / count(*) As moneyInPlay")
->groupBy("Date(ts)")
->orderBy("Date(ts)")
->get()
->toArray();
this is in blade pages
@php
foreach ($statsMoneyInPlay as $key => $value) {
echo "[".$value[0].", ".$value[1]."],";
@endphp
Upvotes: 1
Views: 255
Reputation: 559
The query you're looking for should look a little more like this:
$statsMoneyInPlay = DB::table('enginepoker_log.poker')
->select(
DB::raw("UNIX_TIMESTAMP(Date(ts)*100) as timestamp"),
DB::raw("SUM(pot + p1pot + p2pot + p3pot + p4pot + p5pot + p6pot + p7pot + p8pot + p9pot) / count(*) As moneyInPlay")
)
->groupBy(DB::raw("DATE(ts)"))
->orderByRaw("DATE(ts)")
->get()
->toArray();
In blade, you can access the elements by doing this:
foreach($statsMoneyInPlay as $stat) {
echo "[" . $stat->timestamp . ", " . $stat->moneyInPlay . "]";
}
Upvotes: 1