设置索引'id'在CakePHP's查找('all')方法


Setting the index with 'id' in CakePHP's find('all') method

我有一个数据数组,所有数据都有自己唯一的ID。我使用ORM方法find('all'),结果数组看起来有点像这样:

Array
(
    [0] => Array
        (
            [Wijken] => Array
                (
                    [id] => 1
                    [name] => Naam
                    [lat] => 13.37
                    [lon] => 13.37
                    [zoom] => 14
                )
        )
)

从我的路由我收到一个唯一的ID..我想要的是重新使用我的数组从ID 1中获取数据。

所以我需要的是我的关联数组(由find(")返回)的索引被设置为"Wijken"对象本身的id。

我解释了一切,以防人们有不同的方法。使用参数ID再次查询数据库是不可接受的。

try Set::combine

维护find('all')结构(来自icc97注释):

$idsAsIndexes = Set::combine($wijkens, '{n}.Wijken.id', '{n}');

或者您也可以提取单个模型:

$idsAsIndexes = Set::combine($wijkens, '{n}.Wijken.id', '{n}.Wijken');

希望这是你正在寻找的:)

我不知道有任何方法让你的id作为数组中的键,甚至不认为这是可能的蛋糕没有做一些"有趣的"。

但是如果你做了find all,我不得不假设你要处理数据并在某个时候做一个循环,这时你可以像这样:

foreach ($wijkens as $wijken) {
    [...]do the general things here[...]
    if ($wijken['Wijken']['id'] == $url_id) {
        [...]do the thing you want to specifically do to id = 1 here[...]
    }
}

另一方面,我理解您不想要任何额外的查询,尽管这对我来说似乎是一个相对较小的交易成本,并且仍然是我更喜欢的。