Cakephp 3 belongsToMany不会带来任何结果

zazmityj  于 2022-11-11  发布在  PHP
关注(0)|答案(1)|浏览(169)

我有以下表格
用户公司
我有一个名为users_companies的多对多表
在“用户”(Users)表中,我有:

$this->belongsToMany('Companies', [
        'targetForeignKey' => 'company_id',
        'foreignKey' => 'user_id',
        'joinTable' => 'users_companies',
    ]);

但做

$result = $this->find('all', array(
            'conditions' => array(
                'Users.id' => 1,
            ),
 ))->contain(['Roles', 'Companies']);

它不会给多对多公司带来任何影响。
在query.log上,我看到以下内容:

SELECT
    UsersCompanies. ID AS "Companies_CJoin__id",
    UsersCompanies.user_id AS "Companies_CJoin__user_id",
    UsersCompanies.company_id AS "Companies_CJoin__company_id",
    Companies. ID AS "Companies__id",
    Companies. NAME AS "Companies__name",
    Companies.user_id AS "Companies__user_id",
    Companies.created AS "Companies__created",
    Companies.modified AS "Companies__modified",
    Companies.reason_type AS "Companies__reason_type",
    Companies.fantasy_name AS "Companies__fantasy_name",
    Companies.document_type AS "Companies__document_type",
    Companies.document_id AS "Companies__document_id",
    Companies.avatar AS "Companies__avatar"
FROM
    companies Companies
INNER JOIN users_companies UsersCompanies ON Companies. ID = (UsersCompanies.company_id)
WHERE
    (
        UsersCompanies.user_id IN (1)
        AND Companies. ID = NULL
    )

我想知道我做错了什么,因为在Where子句中,它添加了Companies.id = NULL。因此,它不会带来Companies。

lo8azlld

lo8azlld1#

我留下了一些可以帮助你的步骤:
1.这些模型是手工创建的吗?
bake console可以帮助减少错误。
1.联接表应命名为companies_users,而不是users_companies。您可以阅读数据库约定。
1.检查您的UsersCompaniesTable.php(如果您接受了我在步骤2中的建议,它应该是CompaniesUsersTable.php)。它应该如下所示:

$this->belongsTo('Users', [
    'foreignKey' => 'user_id',
    'joinType' => 'INNER',
]);
$this->belongsTo('Companies', [
    'foreignKey' => 'company_id',
    'joinType' => 'INNER',
]);

相关问题