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'];
    }
?>

これを実行すると、次の 2 つのクエリが生成され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')

なぜこれが起こっているのか分かりません。これを1つのクエリに貼り付けて、Friendships(メンバー関係を介して)どこからレコードを取得するか、Friendships.friend_idまたはFriendships.member_idある場所からレコードを取得する方法はあり6ますか?

4

0 に答える 0