表不使用选项加入 find()

Tables not joining using options to find()

我正在尝试在控制器中加入以下两个 table:

artifacts_publications
----------------------
id
artifact_id
publication_id

authors_publications
--------------------
id 
author_id
publication_id

其他 table 具有 belongsTo 和 HasMany 等关联的设置可以使用 contain() 轻松加入。对于这些 table,假设没有定义任何关联。最后,我想将另一个 table 加入到这些 table 的加入中,但现在我无法将这两个加入。

控制器使用

    namespace App\Controller;
    use App\Controller\AppController;
    use Cake\ORM\TableRegistry;
    use Cake\Datasource\ConnectionManager;

在控制器的index()动作中,我有

$options['joins'] = [
    [
        'table' => 'authors_publications',
        'alias' => 'j',
        'type' => 'LEFT OUTER',
        'conditions' => [
            'authors_publications.publication_id = artifacts_publications.publication_id',
        ],
    ],
];

$query = TableRegistry::getTableLocator()->get('artifacts_publications')->find('all', $options);
$query->limit(2);

debug($query);
debug($query->toArray());

生成的 SQL 查询有点像这样,但我缩短了长标识符:

SELECT id, artifact_id, publication_id 
FROM artifacts_publications
LIMIT 2;

执行该查询也显示没有连接。我尝试关注 cakePHP table joining two tables issue 但我仍然无法加入。手写 SQL 有效,但不够优雅。我在这里错过了什么?

@Utsav

通过将 'join' 切换为 'contain' 来尝试使用 CakePHP 的 Containable 行为。

$options = [
            'fields' => [
                'ArtifactsPublication.fieldsYouWant'
            ],
            'conditions' => [
                'ArtifactsPublication.id' => $artifactId
            ],
            'contain' => [
                'AuthorsPublication'
            ]
        ];

您还可以设置递归来定义是否要获取包含模型的链接模型。或者,您可以在 fields 选项中指定您想要从 artifacts_publications 模型中获取哪些字段,然后仅 contain authors_publications 模型。

希望这对我有帮助,因为我在 CakePHP 中有过手动连接的糟糕经历,而且 CakePHP 标准是使用 contain。请注意 contain 无法检索远程连接数据。

伙计干杯:)