問(wèn)題描述
我正在使用doctrine 2.1來(lái)為settings
表創(chuàng)建一個(gè)模型:
I am using doctrine 2.1 in order to create a model for settings
table:
id | arg | value | category
1 | name | foo | general_settings
2 | desc | bar | general_settings
假設(shè)我有很多不同類別的設(shè)置.為了獲得特定類別的所有設(shè)置,我執(zhí)行以下操作:
Suppose that I have a lot of setting for different categories. In order to get all the setting for a specific category I do something like this:
$q = Doctrine_Query::create()
->from('Setting p')
->where('p.category = ?', $category_name);
此時(shí)一切正常.嗯.. 64,000 美元的問(wèn)題是:是否存在允許我讀取如下結(jié)果的數(shù)據(jù)訪問(wèn)替代方案?
Everything works fine at this point. Well.. the question of $64,000 is: Do exist a data access alternative that allow me to read the result as below?
$resultSet = $q->execute();
//the magic here could be use the -arg- column as index
$requested_setting = $resulSet['name']
//print the setting value
echo $requested_setting['value']; //should prints "foo"
//another way
echo $resulSet['desc']['value']; //should prints "bar"
推薦答案
我明白了:這里的訣竅是使用 INDEX BY
詞.
I got it: the trick here is use the INDEX BY
word.
導(dǎo)入 Query 類(并非總是可選的):
import the Query class (no always optional):
use DoctrineORMQuery;
創(chuàng)建查詢:
$query = $this->data->em->createQuery('
SELECT s
FROM modelsSetting s
INDEX BY s.arg //to set array custom key
WHERE s.category = :category');
$query->setParameter('category', 'general');
設(shè)置隱藏模式以使用只讀數(shù)組
set the hidration mode in order to work with read-only arrays
$settings = $query->getResult(Query::HYDRATE_ARRAY);
顯示值:
echo $settings['desc']['value']; // prints "bar"
查詢構(gòu)建器
使用 QueryBuilder
對(duì)象,您可以在 from
語(yǔ)句中設(shè)置索引:
QueryBuilder
With the QueryBuilder
object you can set the index at the from
statement:
$qb = $em->createQueryBuilder();
$qb->select('s');
$qb->from('modelsSettings', 's', 's.arg'); // here the magic
$result = $qb->getQuery()->getResult();
然后,您可以通過(guò)以下方式訪問(wèn)該對(duì)象:
Then, you can access the object as:
$description = $result['desc'];
$value = $description->getValue();
這篇關(guān)于在學(xué)說(shuō)中使用列值作為數(shù)組索引的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!