cakephp——根据上下文查询模型


Cakephp-Querying models according to context

我需要这样做。

$model="MyModel";
$results=$this->"MyModel"->find("all);

所以我需要根据情况调用不同的函数。我怎么才能做到呢?

你要做的是根据条件调用不同的模型,对吗?

$model = "Model";
$results = $this->{$model}->find('all');

然而,如果你发现自己需要这样做,这可能是因为你的代码组织不正确。你可能想看看其他选择。

可以在控制器动作

中实现
class MyControllerController extends AppController
{
    function action_name()
    {
        $this->uses = array(
            'MyModel',
            'AnotherModel'
        );
        $this->AnotherModel->find('all');
    }
}

$model =" model ";$results = $this->{$model}->find('all');

根据CakePHP编码惯例,使用这种方法是可以的,并且没有更好或更干净的替代方法。特别是当您编写具有复杂逻辑的行为时。所以坚持下去,别担心。