Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

php - Using column value as array index in doctrine

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 

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);

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"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I got it: the trick here is use the INDEX BY word.

Query class

import the Query class (no always optional):

use DoctrineORMQuery;

create the query:

$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');

set the hidration mode in order to work with read-only arrays

$settings = $query->getResult(Query::HYDRATE_ARRAY); 

Display the value:

echo $settings['desc']['value'];  // prints "bar"

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();

Then, you can access the object as:

$description = $result['desc'];
$value = $description->getValue();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...