我正在尝试获取特定的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_id
或Friendships.member_id
为6
的记录?