Alexandre Ferreira
Alexandre Ferreira

Reputation: 65

How can I do a join with last entries in CakePHP?

So, I'm trying to do a query to get the last entries of each user using CakePHP relationship. In my Map and User model I have:

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

And I'm trying to doing this query to catch the last entry of each user. dg_maps and dg_users have a many to many relation.

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;

What I'm doing now is:

$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');

But, I know that a better method then this, using Cake methods. So, how can I do this?

Thank you all!

Upvotes: 1

Views: 103

Answers (1)

miha
miha

Reputation: 25

I used this for my project it is very simple

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

So put this in your model (note for function arguments - there is error in function from link )

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;

}

and you can call this function from your controller You have example in link

Upvotes: 1

Related Questions