I have this query:
select count(*) as total_count, sum(total) as total_value, status from invoice group by status;
when I execute it in the database I get the following:
I want to achieve the same using Doctrine2 but the following code only returns one row:
$rsm = new ResultSetMapping();
$rsm->addScalarResult('total_count', 'totalCount');
$rsm->addScalarResult('total_value', 'totalValue');
$rsm->addScalarResult('status', 'status');
$query = $this->getObjectManager()->createNativeQuery('
select count(*) as total_count, sum(total) as total_value, status from invoice group by status', $rsm);
$result = $query->getResult();
return $result;
This is the result of the above:
array (size=1)
0 =>
array (size=3)
'totalCount' => string '1432' (length=1)
'totalValue' => string '55447.80999999999' (length=2)
'status' => string 'paid' (length=4)
You should use:
$result = $query->getScalarResult();
Instead of :
$result = $query->getResult();
Hope this help
Because you are using getResult doctrine will try to fetch all matching rows for you. You need to use Doctrine's getSingleResult if you don't want the result to be an array of arrays.
So for you simply:
$result = $query->getSingleResult();
You can also limit the number of results to throw a QueryException if more or none are returned:
$query->setMaxResults(1);
Related
I have written in one SQL query and it's working fine. How do I write this in codeigniter?
$sql = "SELECT *
FROM single_message
WHERE
( school_id='$schoolId' AND
classId='$classId' AND
sectionId='$sectionId' AND
sender_id='$senderId' AND
receiver_id ='$receiverId'
) OR
( chool_id='$schoolId' AND
classId='$classId' AND
sectionId='$sectionId' AND
sender_id='$receiverId' AND
receiver_id ='$senderId'
)
ORDER BY messageId DESC"`;
This is what I've tried:
$condition = array(
'school_id' => $schoolId,
'classId' => $classId,
'sectionId' => $sectionId,
'sender_id' => $senderId,
'receiver_id' => $receiverId
);
$this->db->select('*');
$this->db->where($condition);
return $this->db->get('single_message')->result_array();
As per your SQL query:
$sql = "SELECT * FROM single_message WHERE (school_id='$schoolId' AND classId='$classId' AND sectionId='$sectionId' AND sender_id='$senderId' AND receiver_id ='$receiverId') OR (chool_id='$schoolId' AND classId='$classId' AND sectionId='$sectionId' AND sender_id='$receiverId' AND receiver_id ='$senderId') ORDER BY messageId DESC";
There are two ways to write queries. I will explain both way one by one:
Solution 1st:
You can simply just put your condition in where clause like explained below->
$condition = "(school_id='$schoolId' AND classId='$classId' AND sectionId='$sectionId' AND sender_id='$senderId' AND receiver_id ='$receiverId') OR (chool_id='$schoolId' AND classId='$classId' AND sectionId='$sectionId' AND sender_id='$receiverId' AND receiver_id ='$senderId')";
$this->db->select('*');
$this->db->where($condition);
return $this->db->get('single_message')->result_array();
Here you can see that I have passes complete where condition in a string format. This is the fisrt solution. Another method to write this query is.
Solution 2nd:
Query grouping-> It allows you to create groups of WHERE clauses by enclosing them in parentheses. So query would be like:
$condition['AND'] = array(
'school_id' => $schoolId,
'classId' => $classId,
'sectionId' => $sectionId,
'sender_id' => $senderId,
'receiver_id' => $receiverId
);
$condition['OR'] = array(
'school_id' => $schoolId,
'classId' => $classId,
'sectionId' => $sectionId,
'sender_id' => $receiverId,
'receiver_id' => $senderId
);
$this->db->select('*');
// Starts first group
$this->db->group_start();
// AND condition placed in below line
$this->db->where($condition['AND']);
// First group ends here
$this->db->group_end();
// Another group has been started here for OR clause
$this->db->or_group_start();
// Here we placed our OR codition
$this->db->where($condition['OR']);
// Second group ends here
$this->db->group_end();
return $this->db->get('single_message')->result_array();
It will produce exact result you needed. Let me know if you have any query. For more details you can read Query Builder explaination here: Query Grouping
Passing second parameters as null and third parameter as false will result is not escaping your query.
Try this code:
$this->db->select('*');
$this->db->where("school_id='$schoolId' AND classId='$classId' AND sectionId='$sectionId' AND sender_id='$senderId' AND receiver_id ='$receiverId') OR (chool_id='$schoolId' AND classId='$classId' AND sectionId='$sectionId' AND sender_id='$receiverId' AND receiver_id ='$senderId'", null, false);
$this->db->order_by("messageId", "desc");
$this->db->get();
Here is Where reference from codeigniter documentation.
This peace of code is driving me crazy for last hour...
I have this model which should return all non active records from DB
$query = $this->db->get($tableName);
echo $this->db->last_query();
var_dump($query->result());
$this->db->last_query() output is
SELECT * FROM `locations` LEFT JOIN `provinces` ON `provinces`.`id_province` = `locations`.`id_province` LEFT JOIN `countries` ON `countries`.`id_country` = `provinces`.`id_country` LEFT JOIN `statuses` ON `statuses`.`id_status` = `locations`.`id_status` WHERE `locations`.`active` = '0' ORDER BY `locations`.`id_location` DESC LIMIT 50
If i run exactsame query in phpmyadmin i get correct results
But when i var_dump data var_dump($query->result()); i get the following results
array (size=50)
0 =>
object(stdClass)[61]
public 'unique_id' => string 'OWYwYjBmNm' (length=10)
public 'active' => string '1' (length=1)
public 'owner_name' => string 'Cleve Greenfelder' (length=17)
1 =>
object(stdClass)[62]
public 'unique_id' => string 'YWY4YmMzMm' (length=10)
public 'active' => string '1' (length=1)
public 'owner_name' => string 'Bradford Hyatt' (length=14)
Why/how this active state get's overwritten from 0 to 1?
IF you need any additional information's, please let me know and i will provide. Thank you!
Once i wrote a question, answer quickly appeared in my head :)
Table Countries has also active field, so this field overwrites active state as enabled. I needed to specified fields and there's name in query in order to get proper results
$fields = 'unique_id, locations.active as active, ....';
I have this code in laravel to get the products that will run out soon.
$productos = DB::table('productos')
->where('producto_minimo', '>=', 'producto_cantidad')
->get();
And what I get is the following result
which is not the right result. While in MySql I get the right results whith this query SELECT * FROM productos where producto_minimo >= producto_cantidad;
Update
The query log - DB::getQueryLog() - shows this
2 =>
array (size=3)
'query' => string 'select * from `productos` where `producto_minimo` >= ?' (length=54)
'bindings' =>
array (size=1)
0 => string 'producto_cantidad' (length=17)
'time' => float 1
I assume you've got to use the whereRaw method:
$productos = DB::table('productos')
->whereRaw('producto_minimo >= producto_cantidad')
->get();
Your query will compare the value in the column producto_minimo with the string 'producto_cantidad'
Have a look at Eloquents documentation of advanced wheres:
DB::table('users')
->whereExists(function($query)
{
$query->select(DB::raw(1))
->from('orders')
->whereRaw('orders.user_id = users.id');
})
->get();
The query above will produce the following SQL:
select * from users
where exists (
select 1 from orders where orders.user_id = users.id
)
How to achieve this query in phalcon using query builder (best method):
$results = "select * from table where name like 'A%' limit 10"; // <-- 10 records
$total = "select count(1) from table where name like 'A%'"; // <-- 100 records
return [
'data' => $result,
'total' => $total
];
im extjs user and i need to get total over limit to display paging information (eq: displaying 1 to 10 from 100 records)
thx.
You can achieve this with Pagination, see here: Pagination Docs
Only thing is to use QueryBuilder adapter. But this can be done with:
$builder = $this->modelsManager->createBuilder()
->from('Table')
->andWhere('name like :name:', array('name' => 'A%' ) );
$paginator = new Phalcon\Paginator\Adapter\QueryBuilder(array(
"builder" => $builder,
"limit"=> 10,
"page" => 1
));
return [
'data' => $paginator->items,
'total' => $paginator->total_items
];
What I'm trying to do is search through my table and count the instances of a letter, and store the ID of each instance in mysql and php (PDO).
What I had been messing around with is this:
$user = 'john';
$stmt = $pdo->prepare("SELECT id, SUBSTR(surname, 1, 1) as surname_init,COUNT(*) as count FROM first_table WHERE user = :user GROUP BY surname_init ORDER BY count DESC");
$stmt->bindValue(":user", $user);
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($row);
This is the result:
array (size=2)
0 =>
array (size=3)
'id' => string '3' (length=1)
'surname_init' => string 'B' (length=1)
'count' => string '2' (length=1)
1 =>
array (size=3)
'id' => string '7' (length=1)
'surname_init' => string 'D' (length=1)
'count' => string '1' (length=1)
So I have two results: B has 2 instances, D has one. However "B" has only one resulting id returned from two.
Is this possible? I think I'm missing something here..
Use GROUP_CONCAT() to get all rows that matched the group by, like:
SELECT
GROUP_CONCAT(id) AS id_list,
SUBSTR(surname, 1, 1) as surname_init,
COUNT(*) as count
FROM first_table
WHERE user = :user
GROUP BY surname_init
ORDER BY count DESC
See if this helps:
$user = 'john';
// use this to get unique starting characters for surnames for the user John
$stmt = $pdo->prepare("SELECT SUBSTR(surname, 1, 1) as `surname_init`,
COUNT(*) as `count` FROM first_table
WHERE user = :user GROUP BY
surname_init ORDER BY count DESC");
$stmt->bindValue(":user", $user);
$stmt->execute();
$rows1 = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows1 as $row1){
echo "<BR>Starting Letter: " . $row1['surname_init'];
echo "<BR>Count: " . $row1['count'];
// now get all the IDs for this user that have the
// surnames starting with this alphabet
$stmt = $pdo->prepare("SELECT ID, SUBSTR(surname, 1, 1) as `surname_init`,
FROM first_table
WHERE user = :user
AND surname LIKE :surname");
$stmt->bindValue(":user", $user);
$stmt->bindValue(":surname", $row1['surname_init']."%");
$stmt->execute();
$rows2 = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows2 as $row2){
// do insert based on ID here
}
}