1

我正在尝试获取特定的 SQL JOIN (MySQL),但我不太确定如何在 Lithium 中实现它。

我有 3 个模型:

<?php
    class Members extends \lithium\data\Model {

        public $hasMany = [
            'Friendships' => [
                'constraints' => [
                    'or' => [
                        ['Friendships.member_id' => 'Members.id'],
                        // I had to quote `Friends.id` this way because there is no direct relationship
                        // with Members. Got this from the unit tests.
                        ['Friendships.friend_id' => "'Friends.id'"]
                    ]
                ]
            ]
        ];

        /**
         * Returns all the Friends of the currently logged in member using the Friendships relation.
         */
        public static function friends() {
            // @assumption Current Members.id = 6
            return static::find(6, [
                'with' => ['Friendships.Friends']
            ]);
        }
    }
?>

<?php
    /**
     * The relevant fields to this question that this model has are:
     *  - id
     *  - member_id
     *  - friend_id
     */
    class Friendships extends \lithium\data\Model {

        public $belongsTo = ['Members', 'Friends'];
    }
?>

<?php
    class Friends extends \lithium\data\Model {

        public $hasMany = ['Friendships'];
    }
?>

当我执行时,这会生成两个查询Members::friends()

SELECT DISTINCT(`Members`.`id`) AS _ID_
FROM `users` AS `Members`
LEFT JOIN `friendships` AS `Friendships`
    ON (
        (`Friendships`.`member_id` = `Members`.`id`)
        OR
        (`Friendships`.`friend_id` = 'Friends.id')
    )
    AND `Members`.`id` = `Friendships`.`member_id`
LEFT JOIN `users` AS `Friends`
    ON `Friendships`.`friend_id` = `Friends`.`id`
    WHERE `Members`.`id` = '6'
LIMIT 1


SELECT *
FROM `users` AS `Members`
LEFT JOIN `friendships` AS `Friendships`
    ON (
        (`Friendships`.`member_id` = `Members`.`id`)
        OR
        (`Friendships`.`friend_id` = 'Friends.id')
    )
    AND `Members`.`id` = `Friendships`.`member_id`
LEFT JOIN `users` AS `Friends`
    ON `Friendships`.`friend_id` = `Friends`.`id`
WHERE `Members`.`id` IN ('6')

不知道为什么会这样。知道如何将其粘贴到一个查询中并从Friendships(通过成员关系)获取记录吗Friendships.friend_idFriendships.member_id6

4

0 回答 0