php - 如何从数组中的 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 中使用它会受到赞赏。
解决方案
没关系,我想通了。如果您删除 appends 变量和访问器方法,那么它会自动将其附加到对象。但我仍然无法弄清楚为什么我不能在 where 子句中使用距离。
实际上,我在这里也找到了在 where 子句中使用距离的答案。简短的回答,您必须在 where 子句中再次进行计算,因为模型不知道自定义列。
推荐阅读
- kubernetes - Kubernetes 的健康检查如何与 Istio 一起工作?
- react-native - ReactNative ScrollToIndex 太慢了
- sql - 如何知道包含特定键的 JSON 列表?
- android-studio - Android Studio中的Flutter编译错误
- angular - 使用一个调用 observable 的函数,其中 3 个不同的 observable 与 switch map 绑定在一起。导致错误
- python - 为什么我在使用 BeautifulSoup.find_all 函数时添加了 '/' 字符?
- binding - 使用 Azure 函数绑定时如何减少 CreateTable 事务?
- javascript - 如何从html文件中的linux路径加载json文件
- sql - 根据 SQL Server 中的特定条件对行进行分组
- java - Socket Python-Server and Java - android studio中的客户端,其中java无法连接到python服务器