CakePHP访问二级关联数据

CakePHP访问二级关联数据,cakephp,associations,Cakephp,Associations,我有属于某个类别的事务,可以有一个Fuelup。加油属于汽车和交易: 我的表格如下: transactions id|category_id|description categories id|name cars id|name|numberplate fuelups transaction_id|car_id|amount|mileage 在事务的索引功能中,我希望对所有事务进行索引,并显示(如果存在)Fuelup: public function index(

我有属于某个类别的事务,可以有一个Fuelup。加油属于汽车和交易:

我的表格如下:

transactions id|category_id|description
categories   id|name
cars         id|name|numberplate
fuelups      transaction_id|car_id|amount|mileage
在事务的索引功能中,我希望对所有事务进行索引,并显示(如果存在)Fuelup:

public function index() {
     $this->set('transactions', $this->Transaction->find('all'));
}
如何在此视图中访问汽车的名称?我可以毫无问题地使用$transaction['Fuelup']['car_id'],但无法访问$transaction['Fuelup']['car']之类的


我正在运行最新版本的CakePHP 2.3.1。

您必须设置递归性级别。你可以做:

$this->find('all',array('recursive' => 2));
递归属性定义了CakePHP通过find和read方法获取相关模型数据的深度


请参阅烹饪手册。

您必须设置递归性的级别。你可以做:

$this->find('all',array('recursive' => 2));
递归属性定义了CakePHP通过find和read方法获取相关模型数据的深度


请参阅烹饪手册。

不要像Hugo指定的那样使用递归,而应该研究其行为。将其附加到AppModel中,如下所示:

然后,当您进行查找时,您可以执行以下操作:

class AppModel extends Model {
    $transactions = $this->Transaction->find('all', array(
        'contain' => array(
            'Fuelup' => array(
                'Car'
            )
        )
    ));
    $this->set('transactions', $transactions);
}

Containable效率更高,因为它只获取您指定的数据,而recursive会带回您不需要的数据,从而浪费资源。

与Hugo指定的使用recursive相比,您应该研究其行为。将其附加到AppModel中,如下所示:

然后,当您进行查找时,您可以执行以下操作:

class AppModel extends Model {
    $transactions = $this->Transaction->find('all', array(
        'contain' => array(
            'Fuelup' => array(
                'Car'
            )
        )
    ));
    $this->set('transactions', $transactions);
}

Containable效率更高,因为它只获取您指定的数据,而recursive会带回您不需要的数据,从而浪费资源。

为了使它完整:如果您想使用findById,可以使用$this->Car->recursive=2$car=$this->car->findById$id;将事务数据保存在汽车的fuelups中,并使其完整:如果您想使用findById,可以使用$this->car->recursive=2$car=$this->car->findById$id;我理解你的方法,我也通过搜索找到了这个解决方案,但我无法让它运行。我需要在哪里定义fuelups还应该包含各自的汽车?您已经建立了必要的关联。如果你想更深入一层,并得到汽车以及,检查我的编辑。这就是你的意思吗?你不能让它运行是什么意思?你有任何错误吗?我没有设置AppModel Containeable,只是设置TransactionController。由于加油没有控制住,我没有车。现在它就像一个魅力,非常感谢你!没问题,很高兴你弄明白了我理解你的方法,我也通过搜索找到了这个解决方案,但我无法让它运行。我需要在哪里定义fuelups还应该包含各自的汽车?您已经建立了必要的关联。如果你想更深入一层,并得到汽车以及,检查我的编辑。这就是你的意思吗?你不能让它运行是什么意思?你有任何错误吗?我没有设置AppModel Containeable,只是设置TransactionController。由于加油没有控制住,我没有车。现在它就像一个魅力,非常感谢你!没问题,很高兴你弄明白了