I've got two tables in my SQL database. Both have a period_from column as the common date format. Both tables have data back dating for several weeks, I've joined my tables, and am selecting the appropriate columns that I need.
Everything works great and gives me the correct data, but as soon as I add whereDate() I get nothing, an empty array. I've tried the bogstandard where() and have also tried targetting my table followed by my column, e.g: *.period_from, not sure why it's not giving me any results here.
$from = Carbon::now()->subDays(14);
$to = Carbon::now();
$order = 'asc';
$data = DB::table('data_source_one as DGA')
->join('data_source_two as DLCA', 'DGA.created_at', '=', 'DLCA.created_at')
->where('event_action', 'Step 1 Loaded: (Loan Details)')
->select('event_count', 'sessions', 'leads', 'DGA.created_at', 'DGA.period_from', 'DGA.period_to')
->whereDate('DGA.period_from', '>=', $from)
->whereDate('DGA.period_to', '<=', $to)
->orderBy('DGA.created_at', $order)
->get();
you can just do this :
$from = Carbon::now()->subDays(14);
$to = Carbon::now();
$order = 'asc';
$data = DB::table('data_source_one as DGA')
->join('data_source_two as DLCA', 'DGA.created_at', '=', 'DLCA.created_at')
->where('event_action', 'Step 1 Loaded: (Loan Details)')
->select('event_count', 'sessions', 'leads', 'DGA.created_at', 'DGA.period_from', 'DGA.period_to')
->where('DGA.period_from', '>=', $from)
->where('DGA.period_to', '<=', $to)
->orderBy('DGA.created_at', $order)
->get();
Related
I have this query:
return DB::table('electricity_meters')
->where('electricity_meters.id', 16)
->leftJoin('service_instances', 'service_instances.electricity_meter_id', '=', 'electricity_meters.id')
->leftJoin('readings', 'electricity_meters.kwh_param_id', '=', 'readings.parameter_id')
->where('readings.taken_at', '>', 'service_instances.active_to')
->select([
'readings.taken_at',
'service_instances.active_to',
])
->get();
Pay attention to 'readings.taken_at', '>', 'service_instances.active_to', but somehow results are...
[
{
taken_at: "2021-02-16 23:59:59",
active_to: "2021-03-28"
},
...
]
what am I missing here?
I think you want to compare between two columns, if that, you should use whereColumn:
return DB::table('electricity_meters')
->where('electricity_meters.id', 16)
->leftJoin('service_instances', 'service_instances.electricity_meter_id', '=', 'electricity_meters.id')
->leftJoin('readings', 'electricity_meters.kwh_param_id', '=', 'readings.parameter_id')
->whereColumn('readings.taken_at', '>', 'service_instances.active_to')
->select([
'readings.taken_at',
'service_instances.active_to',
])
->get();
I'm sending data to chartist.js using Laravel controller. When I try to join three tables together to sum the values, the output is essentially doubled when I join the third table.
The following query gets the data I need however doesn't sum them accurately
$chart_stats = Transactions::join('customers', 'customers.id', '=', 'transactions.customer_id')
->join('orders', 'orders.customer_id', '=', 'transactions.customer_id')
->distinct()
->select('customers.region', 'transactions.deposit', 'transactions.purchase_total', 'transactions.finance_amount_paid', 'orders.gov_funding_amount')
->whereIn('customers.region', $selected_regions)
->where('transactions.created_at', '>', $from)
->where('transactions.created_at', '<', $to)
->select(
DB::raw('customers.region as region' ),
DB::raw('sum(transactions.deposit) as deposits'),
DB::raw('sum(transactions.purchase_total) as sums'),
DB::raw('sum(transactions.finance_amount_paid) as finance_paid'),
DB::raw('sum(transactions.deposit+transactions.finance_amount_paid) as total_paid'),
DB::raw('sum(orders.gov_funding_amount) as funding')
)
->groupBy('customers.region')
->orderBy('sums', 'asc')
->get();
This will output the following in an array:
#original: array:6 [▼
"region" => "Region 1"
"deposits" => "5025.40"
"sums" => "52875.00"
"finance_amount_paid" => "0.00"
"total_paid" => "5025.40"
"funding" => "9228.00"
It should be:
#original: array:6 [▼
"region" => "Region 1"
"deposits" => "1706.00"
"sums" => "21271.00"
"finance_amount_paid" => "0.00"
"total_paid" => "1706.40"
"funding" => "3396.00"
I was going to give this as a comment but it would be better as a answer. It's a proposition and I could be wrong. There are 2 possible answers.
Change these lines:
->where('transactions.created_at', '>', $from)
->where('transactions.created_at', '<', $to)
To either:
->whereBetween('transaction.created_at, $from, $to)
Or edit: type, arrays into arrays, corrected:
->where([['transactions.created_at', '>', $from], ['transactions.created_at', '<', $to]])
Methink it is possible, if both conditions are true, the row is selected twice. The distinct() may not do what it is intended to do. You could also try a closure:
->where(function ($query) {
$query->where('transactions.created_at', '>', $from)
->where('transactions.created_at', '<', $to)
->distinct();
})
Here is my normal sql query using implode function:
SELECT * from search_result WHERE skills IN ('".implode("','",$s_id)."');
Now I want to convert this to codeigniter form. I tried the following code but it fails
$this->db->from('search_result');
$this->db->where_in('skills','".implode("','",$s_id)."');
$query = $this->db->get();
Here is my $s_id array:
Array ( [0] => 2D Design [1] => 3D Design [2] => 3D Modelling )
So anyone please help me to do this. Thanks in advance :)
Official Doc say's
$names = array('Frank', 'Todd', 'James'); # Data Array
$this->db->where_in('username', $names); # passing array
Try like below
Method 01(recommended )
$this->db->from('search_result');
$this->db->where_in('skills',$s_id);
$query = $this->db->get();
Method 02
$this->db->from('search_result');
$this->db->where_in('skills',implode("','",$s_id));
$query = $this->db->get();
Whats wrong on this line
$this->db->where_in('skills','".implode("','",$s_id)."');
don't wrap function with ' or " quotes. Then it will get save as STRING value to DB.
Links
where_in clause in codeigniter.com
You can just write this :
$this->db->from('search_result');
$this->db->where_in('skills', $s_id);
$query = $this->db->get();
Official doc
$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')
Please help to create a query!
This is a working example of my query Retrieve data as JSON using PHP:
<?php
$con = mysql_connect("localhost","user","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("admin_accounting", $con);
$result = mysql_query("SELECT unix_timestamp(date), sum(ksi2k) FROM accounting where lhc_vo like 'ops' group by year(date), month(date)");
$rows = array();
$rows['type'] = 'area';
$rows['name'] = 'Ops';
while($r = mysql_fetch_array($result)) {
$rows['data'][] = $r[0]*1000;
$rows['data'][] = $r[1];
array_push($rows);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
The JSON results look like this:
{"type":"area","name":"Ops","data":[1167664515000,0,1170342915000,0,1172762115000,0,1175436915000,0,1178028915000,0]}
But I need the JSON results should look like this:
{"type":"area","name":"Ops","data":[[1167664515000,0],[1170342915000,0],[1172762115000,0],[1175436915000,0],[1178028915000,0]]}
I would be very grateful for the help
while($r = mysql_fetch_array($result)) {
$rows['data'][] = array($r[0]*1000, $r[1]);
}
In addition to my other answer, you ought to consider switching away from the ancient (and now deprecated, as of PHP v5.5) ext/mysql. Here is an example using PDO, in which you can see how simple your problem becomes:
<?php
$con = new PDO(
'mysql:hostname=localhost;dbname=admin_accounting',
'user',
'password'
);
$result = $con->query('
SELECT 1000*UNIX_TIMESTAMP(date), SUM(ksi2k)
FROM accounting
WHERE lhc_vo LIKE "ops"
GROUP BY YEAR(date), MONTH(date)
');
print json_encode([
'type' => 'area',
'name' => 'Ops',
'data' => $result->fetchAll(PDO::FETCH_NUM)
]);
?>
Note that:
I have moved the multiplication into the database layer in order that I can simply call fetchAll() to obtain the resulting array;
MySQL will select an indeterminate value from amongst those in each group for the first column in the resultset; should this be undesirable, you will need to apply a suitable aggregate function to the reference to the date column; and
I have used the short array syntax, which is only available from PHP v5.4—if you're using an earlier version, you will need to replace the [ … ] of the argument to json_encode() with array( … ).
There is a way to use agregate functions with cakephp? like sum() or avg() with find() method.
UPDATE:
I missed a line in the book
array('fields'=>array('Product.type','MIN(Product.price) as price'), 'group' => 'Product.type');
Showing the basic structure for doing that.
Thanks for the help
In the fields parameter of a find method call, you may pass the field processed by an aggregated function. Example:
$Model->find('all',
array(
'anything' => array(/* */),
'fields' => array(
'SUM (Model.attribute) AS total',
'OTHERFUNCTION(OModel.other_attribute) AS other'
),
'otherthing' => array(/* */)
)
);
In exactly the same way, since CakePHP is just a PHP framework.
<?php
// Make a MySQL Connection
$query = "SELECT type, SUM(price) FROM products GROUP BY type";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "Total ". $row['type']. " = $". $row['SUM(price)'];
echo "<br />";
}
?>