首页 > 解决方案 > 如何从数组中的 Eloquent 模型中获取自定义列

问题描述

我有一个使用原始 SQL 查询添加到 Eloquent 模型的列,但是在执行 get() 时我无法从模型中取回值。我可以使用 print_r() 打印模型并查看添加到 [attributes:protected] 和 [original:protected] 字段中的值和列,但是当我执行 get() 时它不会返回值。我添加了一个 appends 属性和访问器方法,但它返回 null。前任:

$query = $query->select('*', Capsule::raw('(3959 * acos(
                                                         ( cos( radians( ' . $zip['latitude'] . ' ) )
                                                           * cos( radians( latitude ) )
                                                           * cos( radians( longitude ) - radians( ' . $zip['longitude'] . ' ) ))
                                                         + ( sin( radians( ' . $zip['latitude'] . ' ) )
                                                             * sin( radians( latitude ) ))
                                                   )
                                       ) AS distance')
                                   )->orderBy('distance');

目的:

                    [attributes:protected] => Array
                        (
                            [zip_id] => 11753
                            [zipcode] => 29210
                            [territory_id] => 41
                            [latitude] => 34.04814020
                            [longitude] => -81.10814000
                            [last_verified] => 0000-00-00 00:00:00
                            [nextCheck] => 2020-03-16 17:40:50
                            [active] => 1
                            [distance] => 5.8993697166443E-5
                        )

                    [original:protected] => Array
                        (
                            [zip_id] => 11753
                            [zipcode] => 29210
                            [territory_id] => 41
                            [latitude] => 34.04814020
                            [longitude] => -81.10814000
                            [last_verified] => 0000-00-00 00:00:00
                            [nextCheck] => 2020-03-16 17:40:50
                            [active] => 1
                            [distance] => 5.8993697166443E-5
                        )

回报:

    {
        "zip_id": 11753,
        "zipcode": "29210",
        "territory_id": 41,
        "latitude": "34.04814020",
        "longitude": "-81.10814000",
        "last_verified": "0000-00-00 00:00:00",
        "nextCheck": "2020-03-16 17:40:50",
        "active": 1,
        "distance": null
    }

作为奖励,如果有人可以告诉我为什么我可以在 orderBy 中使用自定义列,但不能在模型的 where 中使用它会受到赞赏。

标签: phplaraveleloquent

解决方案


没关系,我想通了。如果您删除 appends 变量和访问器方法,那么它会自动将其附加到对象。但我仍然无法弄清楚为什么我不能在 where 子句中使用距离。

实际上,我在这里也找到了在 where 子句中使用距离的答案。简短的回答,您必须在 where 子句中再次进行计算,因为模型不知道自定义列。


推荐阅读