-1

我在 cakephp 上开发一个应用插件。我被困在一个功能上,演示如下:

在数据库中,我有一个包含数据的表“平台”('1' => 'PC','2' => 'PS3' ...)。

在游戏视图中,我有:

<? 
$platformes = array($igra['Igra']['pid']); /* gives me 1,2 */
$platforme = $this->requestAction(
    array(
        'plugin' => 'gamer', 
        'controller' => 'Igra', 
        'action' => 'getPlatformaIme'
    ),
    $platformes
); 
?>

在控制器中,我有这样的功能:

function getPlatformaIme($pids) {
    $platforme =  explode(', ', $pids);
    $this->loadModel('Gamer.Platforme');

    foreach($platforme as $pid) {
        $this->Platforme->find('all', array(
            'conditions' => array('Platforme.id' => $pid)
        ));
        $name[] = $this->Platforme->field('name');
    }

    return implode(', ', $name);
}

这应该给我PC,PS3,但它没有。它给了我 PC,即使数组中没有 1。我怎样才能修复我的功能工作?

Tnx 的帮助,这是正确的方法。

功能:

function getPlatformaIme($pids) {
    $platforme[] =  explode(',', $pids);
    $this->loadModel('Gamer.Platforme');

    foreach($platforme as $pid) {
    $names = $this->Platforme->find('list', array(
        'conditions' => array(
            'Platforme.id' => $pid
        )
    ));
    }

    return implode(', ', $names);
}

这给出了数据库中的名称,如果数组是 (1,2) 返回 (PC, PS3)

4

1 回答 1

0

参考文档

查找返回数据,它不会修改对象的状态。如果未使用 find 的返回值,则它会无缘无故地发出 sql 查询。

field期望通过任一条件,或者它将读取当前模型 ID 的字段值。在问题中没有条件并且模型没有设置 id - 因此,有效地,随机记录的名称字段将被多次返回(可能是相同的名称,但不一定)。

在不改变逻辑的情况下更正了代码:

问题中的代码可以更正如下:

function getPlatformaIme($pids) {
    $platforme =  explode(', ', $pids);
    $this->loadModel('Gamer.Platforme');

    foreach($platforme as $pid) {
        $this->Platforme->id = $pid;
        $name[] = $this->Platforme->field('name');
    }

    return implode(', ', $name);
}

使用field也不需要调用 find 。这将返回一个数组,如下所示:

array(
    'One',
    NULL, # <- if the pid doesn't exist
    'Three'
)

使用适当的查找

以上不是获取名称数组的最合乎逻辑的方法,对于这种用例存在find('list') :

function getPlatformaIme($pids) {
    $platforme =  explode(', ', $pids);
    $this->loadModel('Gamer.Platforme');

    return $this->Platforme->find('list', array(
        'conditions' => array(
            'id' => $pids
        )
    ));
}

这将返回一个数组,如下所示:

array(
    1 => 'One',
    3 => 'Three'
)

requestAction 不是必需的

而不是使用请求动作调用请求,调用控制器,调用模型 - 可以直接调用模型:

// anywhere
$names = ClassRegistry::init('Gamer.Platforme')->find('list', array(
    'conditions' => array(
        'id' => $pids
     )
 ));

如果没有缓存元素,则此类代码不应出现在视图中。而是在 beforeRender 函数中,否则很容易编写无法维护的应用程序。

但是,鉴于问题中的代码,它是一种选择。

于 2013-07-09T09:16:26.130 回答