CakePHP 3 在两个表之间关联



我正在尝试在 cakephp 3 中的两个模型(服务器和application_endpoints)表之间创建关联。我想要实现的是将所有数据从表application_endpoints获取到服务器模型。因此,在视图中,我可以访问所有数据。

服务器可以在application_endpoints表中有多个 VIP 和端点,我正在使用 hasMany 关联。所以在服务器表中.php我添加了以下代码:

$this->hasMany('ApplicationEndpoints', [
            'foreignKey' => 'server_id',
            'dependent' => true
        ]);

因此,当我浏览服务器视图页面并单击变量选项卡中的调试工具包时,我没有看到任何连接。我看到数组中的服务器列表,但数组中的每个服务器都没有显示与表application_endpoints任何关系。

发表评论,如果不清楚,请告诉我,我也在链接有关 mysql 模式的 sqlfiddle。

更新 1

我也在ServersTable.php中尝试了这段代码:

$this->belongsTo('ApplicationEndpoints', [
            'bindingKey' => 'server_id',
            'joinType' => 'INNER',
        ]);

所以hasMay是在两个模型之间建立联系的正确方法。

    $this->hasMany('ApplicationEndpoints', [
        'foreignKey' => 'server_id',
        'dependent' => true
    ]);

我不得不在服务器控制器中添加额外的代码才能使其使用以下代码:

    // View method
    $query = $this->Servers->get($id, [
        'contain' => ['ApplicationEndpoints']
    ]);
    $this->set('data', $query);

最新更新