douhuan6305 2014-05-16 14:42
浏览 8
已采纳

选择具有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

enter image description here

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

  • 写回答

1条回答 默认 最新

  • dongyan1491 2014-05-16 15:06
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?