Why does CakePHP wrap database results up in so many subarrays?
CakePHP has an annoying habit of having very deep,开发者_开发知识库 multidimensional arrays when pulling data from the database.
For instance, I simply wanted to get the count of rows returned by a previous query using SQL_CALC_FOUND_ROWS and "SELECT FOUND_ROWS() as row_count". The results were three arrays deep: $result[0][0]['row_count'].
You can use
$this->Model->find('count');
http://book.cakephp.org/view/1020/find-count?
or rewrite query as
"select FOUND_ROWS() as TableName.row_count from tablename TableName"
This is a pretty good question! I'm not sure why CakePHP does this and have wondered the same thing myself. I've only semi-dug into Cake "internals" and haven't went into this aspect of the framework.
If I were to venture a guess...
This is a side effect of Cake's ORM. The ORM that comes with Cake, at least in my opinion, is pretty nice and allows you to make some highly complex queries with virtually little or no raw SQL. I'm sure this is part of the reason for Cake's popularity. It turns complex SQL statements into a relatively simple multi-dimensional array structure, both in creating the query and the data returned.
Another aspect of Cake that might effect this is their "convention over configuration" philosophy. I'm sure it is simpler on the development side to return the same general array structure instead of trying to optimize for raw SQL. I would venture to bet that the majority of Cake queries are produced through the ORM and not raw queries written out by the developer. Optimizing for them might not make sense from a development point of view.
Again, this is just my somewhat-educated guess.
well, first of all, you are using a custom query, and cake has to take care of all the possible cases of returned data (it doesn't know the return data is going to be 1 value). The $result array for example, I would guess the outer most array is for when the returned data are multiple records.
So yeah, it's like that because it follows certain steps to convert from DB result to PHP variable. And it's better for consistency across the whole framework. It's certainly annoying in cases like yours, but you can always define a custom query() function in app_model to intelligently strip out the arrays if there's one single returned value.
精彩评论