选择具有Eloquent值的最后记录

时间:2014-05-16 14:42:19

标签: php mysql sql laravel eloquent

我将字段和值存储在键值样式表中。我希望随着时间的推移存储用户数据的修订版。当我从他们的数据中选择时,我只想要每个键的最新值。

http://sqlfiddle.com/#!2/d7138

enter image description here

我目前急于加载但是当我只想要每个键的最后一个值时,它会选择此数组中的所有键。

    public function healthProfile()
    {
        return $this->hasMany('PortalUserMember', 'portal_user_id')
            ->whereIn('key', [
                'health.profile.sex',
                'health.profile.birthday_day',
                'health.profile.birthday_month',
                'health.profile.birthday_year',
                'health.profile.height_ft',
                'health.profile.height_in',
                'health.profile.weight_lbs',
                'health.profile.contact_street_1',

                            // Could be anything at any point.

                'health.profile.mail_pharmacy_name',
                'health.profile.mail_pharmacy_fax',
                'health.profile.mail_pharmacy_phone'
            ]);
    }

更新

我这样做是为了临时工作:

http://laravel.io/bin/5zn58

1 个答案:

答案 0 :(得分:1)

http://sqlfiddle.com/#!2/d7138/5

SELECT `key`, value FROM portal_user_members pum1
WHERE portal_user_id = 1
AND `key` IN  ('health.profile.sex',
'health.profile.birthday_day',
'health.profile.birthday_month',
'health.profile.birthday_year',
'health.profile.height_ft',
'health.profile.height_in',
'health.profile.weight_lbs',
'health.profile.contact_street_1',
'health.profile.mail_pharmacy_name',
'health.profile.mail_pharmacy_fax',
'health.profile.mail_pharmacy_phone')
AND id = (SELECT MAX(id) 
FROM portal_user_members pum2
WHERE pum2.key = pum1.key)

使用GROUP BY的另一个版本。这可能会更快,具体取决于您为表格编制索引的方式。 http://sqlfiddle.com/#!2/d7138/9

SELECT pum1.key, pum1.value 
FROM portal_user_members pum1
JOIN (
SELECT `key`, MAX(id) id
FROM portal_user_members pum2
WHERE portal_user_id = 1
AND `key` IN  ('health.profile.sex',
'health.profile.birthday_day',
'health.profile.birthday_month',
'health.profile.birthday_year',
'health.profile.height_ft',
'health.profile.height_in',
'health.profile.weight_lbs',
'health.profile.contact_street_1',
'health.profile.mail_pharmacy_name',
'health.profile.mail_pharmacy_fax',
'health.profile.mail_pharmacy_phone')
GROUP BY pum2.key  
) pum2 ON pum2.id = pum1.id