Using column value as array index in doctrine(在学说中使用列值作为数组索引)
问题描述
我正在使用doctrine 2.1来为settings
表创建一个模型:
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);
此时一切正常.嗯.. 64,000 美元的问题是:是否存在允许我读取如下结果的数据访问替代方案?
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.
导入 Query 类(并非总是可选的):
import the Query class (no always optional):
use DoctrineORMQuery;
创建查询:
$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);
显示值:
echo $settings['desc']['value']; // prints "bar"
查询构建器
使用 QueryBuilder
对象,您可以在 from
语句中设置索引:
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();
这篇关于在学说中使用列值作为数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在学说中使用列值作为数组索引
基础教程推荐
- HTTP 与 FTP 上传 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 使用 PDO 转义列名 2021-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01