2014-05-16 44 views
0

我将字段和值存储在键值样式表中。我想随时保存用户数据的修订版。当我从他们的数据中选择时,我只想要每个键的最新值。选择最后一个有价值的记录

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

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 
+0

有没有机会你知道Laravel的Eloquent版本? –

+0

对不起,我不熟悉Laravel或Eloquent – FuzzyTree

相关问题