1

因此,我正在尝试使用 CakePHP 关系进行查询以获取每个用户的最后一个条目。在我的地图和用户模型中,我有:

class Map (and User) extends AppModel {
    public $hasMany = 'Geolog';
}

我正在尝试执行此查询以捕获每个用户的最后一个条目。dg_maps 和 dg_users 具有多对多关系。

SELECT 
    dg_users.id,
    dg_users.email,
    dg_maps.id,
    dg_maps.latitude,
    dg_maps.longitude,
    dg_maps.timestamp
FROM
    (SELECT 
        *
    FROM
        dg_maps
    ORDER BY dg_maps.timestamp DESC) dg_maps
JOIN
    dg_geologs ON dg_geologs.map_id = dg_maps.id
JOIN
    dg_users ON dg_users.id = dg_geologs.user_id
GROUP BY dg_geologs.user_id;

我现在正在做的是:

$this->Map->query('SELECT dg_users.id, dg_users.email, dg_maps.id, dg_maps.latitude, dg_maps.longitude, dg_maps.timestamp FROM (SELECT * FROM dg_maps ORDER BY dg_maps.timestamp DESC) dg_maps JOIN dg_geologs ON dg_geologs.map_id = dg_maps.id JOIN dg_users ON dg_users.id = dg_geologs.user_id GROUP BY dg_geologs.user_id');

但是,我知道使用 Cake 方法比这个更好。那么,我该怎么做呢?

谢谢你们!

4

1 回答 1

1

我将它用于我的项目,非常简单

生成用于分页的 CakePHP HABTM 连接的简单方法。

所以把它放在你的模型中(注意函数参数 - 来自链接的函数有错误)

public function generateHabtmJoin ($joinModel, $joinType = 'INNER') {
// If the relation does not exist, return an empty array.
if (!isset($this->hasAndBelongsToMany[$joinModel])) {
    return array();
}

// Init joins, and get HABTM relation.
$joins = array();
$assoc = $this->hasAndBelongsToMany[$joinModel];

// Add the join table.
$bind = "{$assoc['with']}.{$assoc['foreignKey']} = {$this->alias}.{$this->primaryKey}";
$joins[] = array(
    'table' => $assoc['joinTable'],
    'alias' => $assoc['with'],
    'type' => $joinType,
    'foreignKey' => false,
    'conditions' => array($bind),
);

// Add the next table.
$bind = "{$joinModel}.{$this->{$joinModel}->primaryKey} = {$assoc['with']}.{$assoc['associationForeignKey']}";
$joins[] = array(
    'table' => $this->{$joinModel}->table,
    'alias' => $joinModel,
    'type' => $joinType,
    'foreignKey' => false,
    'conditions' => array($bind),
);

return $joins;

}

你可以从你的控制器调用这个函数你在链接中有例子

于 2013-09-15T20:19:03.150 回答