如何与CakePHP中的最后一个条目进行连接?

时间:2013-09-15 14:20:59

标签: php mysql sql cakephp

所以,我正在尝试使用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方法。那么,我该怎么做呢?

谢谢大家!

1 个答案:

答案 0 :(得分:1)

我在项目中使用它非常简单

Easy way to generate CakePHP HABTM joins for use in pagination.

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

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;

}

您可以从控制器中调用此功能 你有链接

的例子