2014-05-16 80 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

相關問題