我有2个表用户和画廊,关系就像用户hasMany Gallery.But在某些情况下查询用户模型我想获得最新的Gallery行,即ID为2而不是多行的画廊。
Array
(
[User] => Array
(
[id] => 100
[username] => pradeepta
)
[Gallery] => Array
(
[0] => Array
(
[id] => 1
[user_id] => 100
[photo] => 1111.jpg
)
[1] => Array
(
[id] => 2
[user_id] => 100
[photo] => 222.jpg
)
)
)

我希望结果应该像这样
Array
(
[User] => Array
(
[id] => 100
[username] => pradeepta
)
[Gallery] => Array
(
[id] => 2
[user_id] => 100
[photo] => 222.jpg
)
)

答案 0 :(得分:1)
关系仍然需要是hasMany,但您想要更改查询的条件。如果使用连接语句,则可以限制返回的结果: -
$this->User->find(
'first',
array(
'fields' => array(
'User.*',
'Gallery.*'
),
// Join on the galleries table
'joins' => array(
array(
'table' => 'galleries',
'alias' => 'Gallery',
'type' => 'LEFT',
'conditions' => array(
'Gallery.user_id = User.id'
)
)
),
// Order by newest galleries first
'order' => array(
'Gallery.id' => 'DESC'
),
// Make sure we only return one instance of each user
'group' => array(
'User.id'
)
)
);
答案 1 :(得分:0)
在您的用户模型中使用此关联
public $hasOne = array(
'Gallery' => array(
'className' => 'Gallery',
'foreignKey' => 'user_id',
'order' => array('Gallery.id' => 'DESC')
),
);