【问题标题】:Select Last Record With Value With Eloquent使用 Eloquent 选择具有值的最后一条记录
【发布时间】:2014-05-16 14:42:19
【问题描述】:

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

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

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

    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

【问题讨论】:

    标签: php mysql sql laravel eloquent


    【解决方案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
    

    【讨论】:

    • 你有没有机会知道 Laravel 的 Eloquent 版本?
    • 对不起,我不熟悉 Laravel 或 Eloquent
    猜你喜欢
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 2011-08-30
    • 2016-10-08
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    相关资源
    最近更新 更多