【问题标题】:Self linking model in cakePHP 3 and retrieving data from the join tablecakePHP 3 中的自链接模型和从连接表中检索数据
【发布时间】:2016-05-30 10:42:36
【问题描述】:

我正在使用 cakePHP 3.0 创建一个 WebApp。

我有一个用户模型和表,它拥有并属于许多用户。

所以我按照蛋糕惯例摆桌:

CREATE TABLE IF NOT EXISTS `users`
(
user_id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
);

和 JOIN 表:

CREATE TABLE IF NOT EXISTS `users_users`
(
supervisor_id int,
employee_id int,
FOREIGN KEY (supervisor_id) REFERENCES users(user_id),
FOREIGN KEY (employee_id) REFERENCES users(user_id)
);

在我的 UserTable.php 中,我创建了这些关联:

    $this->table('users');
    $this->primaryKey('user_id');

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

    $this->belongsToMany('Supervisors', [
                'className' => 'Users',
                'targetForeignKey' => 'supervisor_id'
    ]);
    $this->belongsToMany('Employees', [
                'className' => 'Users',
                'targetForeignKey' => 'employee_id'
    ]);

现在在一种新的模型方法中,我想获得一名员工的主管:

public function getSupervisorEmail($user_id) {
        $supervisors = $this->Employees->Supervisors->find()->select(['user_id']);
        debug($supervisors);
        return $supervisors;
    }

我将示例数据放在 users_users 表中,但我不知道如何访问这些条目。上面函数中的查询没有做我期望它做的事情。它只是从我的用户表中返回一条记录,而没有加入 users_users 表这是我不明白的,因为我根据 cakePHP 3 的命名约定进行了所有设置......

如何访问我的加入表并获取相关记录? EG 获取与 user_id 1 的用户关联的主管。我尝试了不同的查询,但没有人使用我的联接表。

感谢您的回答!

【问题讨论】:

    标签: php cakephp join cakephp-3.0 has-and-belongs-to-many


    【解决方案1】:

    在 HABTM 的 through 选项中指定连接表对象(在 3.0 中它已重命名为 belongsToMany / BTM)assoc。否则它将根据表名变形并构造一个 Table 对象实例。我会总是创建连接表对象,所以现在就烘焙它。

    http://book.cakephp.org/3.0/en/orm/associations.html#belongstomany-associations

    通过 允许您提供要在连接表上使用的表实例的名称或实例本身。这使得自定义连接表键成为可能,并允许您自定义数据透视表的行为。

    您没有查询其他关联。在您的查询中包含()您的连接表模型。

    http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#eager-loading-associations

    默认情况下,CakePHP 在使用 find() 时不会加载任何相关数据。您需要“包含”或预先加载要在结果中加载的每个关联。

    $query = $articles->find('all');
    $query->contain(['Authors', 'Comments']);
    

    【讨论】:

      【解决方案2】:

      问题是我理解错了。调试查询时的 SQL 语句不会显示 cakePHP 内部发生的所有 SQL 内容,因此您看不到自动连接。

      但现在我发现它可以通过像 cakePHP 书 http://book.cakephp.org/3.0/en/orm/associations.html#belongstomany-associations 中一样回显 testdata 来完美运行

      感谢@burzum 尝试帮助我,提供的链接总是有帮助的。

      【讨论】:

        【解决方案3】:
        $users = $this->Users->find('all', [
                    'order' => [],            
                    'conditions' => ['Users.id' => 1],
                    'contain' => ['Supervisors','Employees']
                        ]
                );
        

        使用这个

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-02-26
          • 2018-09-15
          • 2018-07-20
          相关资源
          最近更新 更多