【问题标题】:CakePHP access 2nd level association dataCakePHP 访问二级关联数据
【发布时间】:2013-03-12 06:37:56
【问题描述】:

我有属于类别交易,并且可以有一个FuelupFuelup 属于 CarTransaction

class Transaction extends AppModel {
    public $belongsTo = array('Category');
    public $hasOne = array('Fuelup');
}

class Fuelup extends AppModel {
    public $belongsTo = array('Transaction','Car');
}

class Car extends AppModel {
        public $hasMany = array('FuelUp');
}

class Category extends AppModel {
    public $hasMany = "Transaction";
}

我的表格如下所示:

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。

【问题讨论】:

    标签: cakephp associations


    【解决方案1】:

    您应该查看 Containable 行为,而不是使用 Hugo 指定的递归。您将其附加到您的AppModel 中,如下所示:

    class AppModel extends Model {
        public $recursive = -1; // disable recursive
    
        public $actsAs = array('Containable');
    }
    

    然后,当您进行查找时,您可以这样做:

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

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

    【讨论】:

    • 我理解你的方法,我也通过搜索找到了这个解决方案,但我无法让它运行。我需要在哪里定义燃料加注也应该包含它们各自的汽车?
    • 您已经设置了必要的关联。如果您想更深入一层并获得汽车,请查看我的编辑。你是这个意思吗?你的意思是你不能让它运行,你有什么错误吗?
    • 我没有设置 AppModel Containable,而只是设置了 TransactionsController。由于加油没有起到 Containable 的作用,我没有得到任何汽车。现在它就像一个魅力,非常感谢你!
    • 没问题,很高兴你明白了
    【解决方案2】:

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

    $this->find('all',array('recursive' => 2));
    

    递归属性定义了 CakePHP 应该通过 find() 和 read() 方法获取关联模型数据的深度。

    参见烹饪手册中的this entry

    【讨论】:

    • 并让它完整:如果你想使用 findById,你可以使用 $this->Car->recursive = 2; $car = $this->Car->findById($id);在汽车的加油中获取交易数据。
    猜你喜欢
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 2013-09-28
    • 2016-03-16
    • 1970-01-01
    • 2014-08-04
    相关资源
    最近更新 更多