简体   繁体   中英

Select Last Record With Value With Eloquent

I'm storing fields and values in a key value style table. I want to store revisions of user data over time. When I select from their data I only want the latest value of each key.

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

在此处输入图片说明

I'm currently eager loading but this selects all keys in this array when I just want the last value for each key.

    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'
            ]);
    }

Update

I'm doing this as a temporary work around:

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

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)

Another version using GROUP BY. This may be faster depending on how you've indexed your tables. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM