Write a fetchAssoc mysql query in Magento 2.

Write a Mysql fetchAssoc() query using Magento standard way for Fetches all the SQL result rows as an associative array as an output.

You can write direct SQL query fetchAssoc() without worrying about Model operation using below code snippet.

Return Type: fetchAssoc() always return as an array with the first column is the key and the entire row array is the value.

Base Definition of function:

Let’s we are writing a query from sales_order table to accomplish fetchAssoc() query operation.

You need to write a custom SQL select query and add that query into fetchAssoc() function same as above fetchAssocQuery() method.

Output:
Here in output, you can see key value is always the first-row value of the table. like 1, 10 and 14 are the entity_id of result and its a first key of sales_order table.

This is the difference between fetchAssoc() and fetchAll().
fetchAll shows the result as a key is 0 based value while fetchAssoc() shows the original key value of the first row in a table.

 

Check for other Direct SQL Query in Magento 2

Leave a Reply