Laravel - use the Eloquent where method from within View - php

In Laravel 5.4, I have these tables:
sales_orders : id,order_code, customer_id
out_transactions : id, ref_id
ref_id refers to the primary key (i.e. id) of sales_orders.
First I need to get all the rows from sales_orders with a particular customer_id i.e. 10; Then for each row, I need to query the out_transactions table matching its ref_id against the id of sales_orders table.
Inside the show_all method of the controller RequisitionController, I have :
$query_sales_order=SalesOrder::where('customer_id',10);
$requisitions = $query_sales_order->get();
$model=InventoryOutTransaction::query();
return view('admin.requisition.requisition',compact('requisitions')->withModel($model);
Inside the requisition.blade.php, I have :
foreach($requisitions as $aP) {
$requisition_id = $aP->id;
$inventory_out_info = $model->where('ref_id', $requisition_id);
echo '<br/> sql = '.$inventory_out_info->toSql();
$inventory_out_result = $inventory_out_info->get();
$inventory_out_info_id = 0;
foreach ($inventory_out_result as $inventory_out_result_indiv) {
$inventory_out_info_id = $inventory_out_result_indiv->id;
echo ' inventory_out_info_id = '.$inventory_out_info_id;
}
}
But the sql shows unexpected query .
What I get in a case is
sql = select * from `out_transactions` where `ref_id` = ?
sql = select * from `out_transactions` where `ref_id` = ? and `ref_id` = ?
sql = select * from `out_transactions` where `ref_id` = ? and `ref_id` = ? and `ref_id` = ?
So you can see that the where clause is being concatenated. And the concatenated clause remembers the 1st, 2nd etc values of ref_id from the for loop to use each of them, I guess ( I just cannot print the exact value of ? in the query).
How can I just remove the concatenation ? or Any other way to achieve the same purpose ?

First try this query in your controller and print the answer once your expected result is come change your controller with this query and pass the result into view page and foreach the results with your need.
$result = DB::table('sales_orders')->join('out_transactions','sales_orders.id','=','out_transactions.ref_id')->where('sales_orders.customer_id',10)->get();

Related

PHP Query - Exclude if exist in table

orderfood
orderfood_id food_id total_amount
foodcancel
foodcancel_id food_id status
$query = $this->db->query("SELECT * FROM order_food of LEFT JOIN `foodcancel` fc ON of.food_id = fc.food_id WHERE of.orderfood_id = '" . (int)$orderfood_id . "'");
$order_foods = $query->rows;
above is my query, what i wanted is that if there food_id inside foodcancel table , exclude it from rows, possbile to do it ?
For exclude the existing values you could try checking null for corresponding matching value
SELECT *
FROM order_food of
LEFT JOIN foodcancel fc ON of.food_id = fc.food_id
and of.food_id = your_value
WHERE fc.orderfood_id is null
anyway you should not php var in your sql code because in this way you are are risk for sqlinjection for avoid this you should take a look at prepared statement and binding param
It's very possible to do. In my logic. first, you must get all food_id on food_cancel table. Then save it into variabel and use it when you show orderFood table with adding NOT IN condition.
I've write code for you,
<?php
// Get Food Id From Cancel
$orderCancel = mysqli_query($mysqli, "SELECT * FROM `foodcancel`");
$cancelId = "";
while ($cancel = mysqli_fetch_array($orderCancel)) {
$cancelId .= $cancel["food_id"].",";
};
$cancelId = substr($cancelId, 0, -1);
// Put Food Id on Cancel Table into NOT IN Condition Database
$orderFood = mysqli_query($mysqli, "SELECT * FROM `orderfood` WHERE food_id NOT IN ($cancelId)");
while ($order = mysqli_fetch_assoc($orderFood)) {
$food[] = $order;
};
echo json_encode($food);
?>

select all rows when search parameter value is null or empty [mysql]

I am trying to use multiple search options where user can select multiple options to filter records.
When user don't select filter option(s), by default all records should be returned.
Here's my SQL query :
$query =
sprintf("SELECT * FROM users_leave_request
where leave_from >= '$leave_from'
AND leave_to <= '$leave_to'
AND leave_status = '$leave_stat'
AND user_id = '$emp_id'");
$result=$this->db->exec($query);
What I intend to do is that:
Suppose $leave_stat parameter is empty, then records for all leave_stat values should be returned.
Similarly if $emp_id is empty, records for all users should be returned.
It's somewhat like disabling that *extra AND* where condition when parameter is empty.
Can I do this with a single query or do I have to use separate queries for that?
Any help is very much appreciated. Thanks.
You can check the filter condition before the query, like this
$whrcondn="";
$whrcondn.=($leave_from)?" and leave_from > = '$leave_from'":"";
$whrcondn.=($leave_to)?" and leave_to < = '$leave_to'":"";
$whrcondn.=($leave_status)?" and leave_status = '$leave_stat'":"";
$whrcondn.=($emp_id)?" and user_id ='$emp_id'":"";
$query = sprintf("select * from users_leave_request where 1=1 $whrcondn");
look at this simple way
add this condition
if(!empty($leave_stat))
{$x='leave_status';}
else
{$x='leave_status!';}
if(!empty($leave_stat))
{$y='user_id';}
else
{$y='user_id!';}
then change leave_status and user_id by $x and $y like this :
$query = sprintf("SELECT * FROM users_leave_request
where leave_from >= '$leave_from'
AND leave_to <= '$leave_to'
AND '$x' = '$leave_stat'
AND '$y' = '$emp_id'");
$result=$this->db->exec($query);
and good luck

PHP/SQL: Faster Way to Combine Query Results

I'm joining data from two SQL queries and I'm wondering if there is a faster way to do this as a single SQL query because there is a lot of looping involved. I've got two queries that look for different string values in the "option_name" field:
$sql01= "SELECT user_id, option_value FROM wp_wlm_user_options WHERE option_name = 'wpm_login_date' ORDER BY user_id";
$sql02 = "SELECT user_id, option_value FROM wp_wlm_user_options WHERE option_name ='stripe_cust_id' ORDER BY user_id ";
Then I create two arrays:
//Process the 1st SQL query data into an Array
$result_array01 = array();
$j = 0;
while($r = mysql_fetch_assoc($result01)) {
if(!empty($r['option_value'])){
//User Id and Last Login
$result_array01[$j]['user_id'] = $r['user_id'];
$result_array01[$j]['last_login'] = $r['option_value'];
$j++;
}
}
//Process the 2nd SQL query data into an Array
$result_array02 = array();
$k = 0;
while($s = mysql_fetch_assoc($result02)) {
if(!empty($s['option_value'])){
//User Id and Stripe Customer Id
$result_array02[$k]['user_id'] = $s['user_id'];
$result_array02[$k]['cust_id'] = $s['option_value'];
$k++;
}
}
And finally, I combine the arrays:
//Combine the SQL query data in single Array
$combined_array = array();
$l = 0;
foreach($result_array01 as $arr01){
// Check type
if (is_array($arr01)) {
//mgc_account_print("hello: " . $arr01['user_id'] . "\r\n");
foreach($result_array02 as $arr02){
// Check type
if (is_array($arr02)) {
//Check if User Id matches
if($arr01['user_id'] == $arr02['user_id']){
//Create Array with User Id, Cust Id and Last Login
$combined_array[$l]['user_id'] = $arr01['user_id'];
$combined_array[$l]['last_login'] = $arr01['last_login'];
$combined_array[$l]['cust_id'] = $arr02['cust_id'];
$l++;
}
}
}
}
}
Why you doing in two different queries?
Use mysql IN('val', 'val2');
$sql01= "SELECT tbl1.user_id, tbl1.option_value FROM wp_wlm_user_options as tbl1 WHERE tbl1.option_name = 'wpm_login_date'
union all
SELECT tbl2.user_id, tbl2.option_value FROM wp_wlm_user_options as tbl2. WHERE tbl2.option_name ='stripe_cust_id' ";
But using OR/AND will your help you in your case , I didnt see at first that you want combined same table. I didnt delete my answer to help you for another solution
Also you should use DISTINCT to avoid multiple records.
SELECT DISTINCT USER_ID, OPTION VALUE FROM TABLE

Codeigniter: display two data in query with distinct and count

I'm try to display two data of one query using codeigniter.
$query = "SELECT count(distinct p.id_paciente), count(c.pacientes_id_paciente) FROM paciente p, cita c WHERE p.id_paciente=c.pacientes_id_paciente AND p.usuarios_id_usuario=43 AND p.aseguradoras_id_aseguradora=8 AND c.dia_cita>='2015-04-16' AND c.dia_cita<='2015-04-16'";
$sql = $this->db->query($query);
How can I to show the two results of count(distinct p.id_paciente) and the count(c.pacientes_id_paciente)
I try using
foreach ($sql->result_array() as $row)
{
echo $row['id_paciente'];
echo $row['pacientes_id_paciente'];
}
But only display the content of the array...
Thanks
There are several issues with your code:
Use aliases to name columns in the resultset to be able to address them later by name
SELECT COUNT(distinct p.id_paciente) AS count1, ...
^^^^^^
Don't interpolate query strings yourself. Use Codeigniter's query bindings
This may not be relevant to you but if dia_cita has time component to it (i.e. is of type datetime) you may want to change your WHERE condition to
c.dia_cita >= ? AND c.dia_cita < ? + INTERVAL 1 DAY
There is no need for foreach loop. You always get only one row with this query. Therefore use Codeigniter's row() or row_array().
That being said your code may look like
$sql = "
SELECT COUNT(DISTINCT p.id_paciente) AS count1,
COUNT(c.pacientes_id_paciente) AS count2
FROM paciente p JOIN cita c
ON p.id_paciente = c.pacientes_id_paciente
WHERE p.usuarios_id_usuario = ?
AND p.aseguradoras_id_aseguradora = ?
AND c.dia_cita >= ?
AND c.dia_cita < ? + INTERVAL 1 DAY
";
$bindings = array(43, 8, '2015-04-16', '2015-04-16')
$row = $this->db
->query($sql, $bindings)
->row_array();
echo $row['count1'], $row['count2'];

Query a column containing Comma Separated String

I am having an issue with an sql query. Basically I have this method:
public function loadByDirectoryContact($directoryContact,$type='')
{
global $db;
$t = 'directoryprogramme';
$query = 'SELECT c.* FROM `'.$t.'` c ';
$query .= 'WHERE `c`.`presenters` = '.$directoryContact->getId().' ';
$query .= 'OR `c`.`staff` = '.$directoryContact->getId().' ';
if($type!=""){
$query .=" AND c.type='".$type."' ";
}
$query .= QueryBuilder::orderBy('name','asc');
echo $query; die();
$db->query($query,$t);
while($db->next($t))
{
$node = new Programme();
$node->setId($db->get('id',$t));
$node->setName($db->get('name',$t));
$node->setBroadcastTime($db->get('broadcast_time',$t));
$node->setDescription($db->get('description',$t));
$node->setDays($db->get('days',$t));
$node->setSubjects($db->get('subjects', $t));
$node->setStaff($db->get('staff',$t));
$node->setPresenters($db->get('presenters',$t));
$directoryCompany = new DirectoryCompany($db->get('directorycompany_id',$t));
$node->setDirectoryCompany($directoryCompany);
$node->setContributors($directoryContact);
$node->setType($db->get('type',$t));
$this->nodes->add($node);
}
}
It creates a query like this:
SELECT c.*
FROM `directoryprogramme` c
WHERE `c`.`presenters` = 1234
OR `c`.`staff` = 1234
ORDER BY `name` ASC
The problem is that the presenters column stores comma seperated values so in reality it looks like this
presenters
1234,7738,5097,5100
and so for any query where the c.presenters equals any value that is not first in this column it returns no results. I am wondering if there is a way I can query so that it checks the entire String?
You can use the function FIND_IN_SET to find your value in the list:
SELECT c.*
FROM `directoryprogramme` c
WHERE FIND_IN_SET('1234',`c`.`presenters`) > 0
OR `c`.`staff` = 1234
ORDER BY `name` ASC
Remark
Consider normalizing your table design, if you can. This means a separate table for the presenters ids with one row per id.
You can also try:
SELECT c.* FROM `directoryprogramme` c WHERE `c`.`presenters` LIKE '%1234%' OR `c`.`staff` = 1234 ORDER BY `name` ASC
I believe the presenters column is in varchar.

Categories