gpt4 book ai didi

php - 在 Doctrine 中使用列值作为数组索引

转载 作者:IT王子 更新时间:2023-10-28 23:59:00 26 4
gpt4 key购买 nike

我正在使用 Doctrine 2.1 为 settings 表创建模型:

id |  arg  |  value  |  category
1 | name | foo | general_settings
2 | desc | bar | general_settings

假设我有很多不同类别的设置。为了获得特定类别的所有设置,我执行以下操作:

$q = Doctrine_Query::create()
->from('Setting p')
->where('p.category = ?', $category_name);

此时一切正常。嗯.. 64,000 美元的问题是:是否存在允许我读取如下结果的数据访问替代方案?

$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 字。

查询类

导入查询类(并非总是可选的):

use \Doctrine\ORM\Query;

创建查询:

$query = $this->data->em->createQuery('
SELECT s
FROM models\Setting s
INDEX BY s.arg //to set array custom key
WHERE s.category = :category');
$query->setParameter('category', 'general');

设置隐藏模式以使用只读数组

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

显示值:

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

查询生成器

使用 QueryBuilder 对象,您可以在 from 语句中设置索引:

$qb = $em->createQueryBuilder();
$qb->select('s');
$qb->from('models\Settings', 's', 's.arg'); // here the magic
$result = $qb->getQuery()->getResult();

然后,您可以通过以下方式访问该对象:

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

关于php - 在 Doctrine 中使用列值作为数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12096792/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com