【问题标题】:CackePHP 3 formatResults() ORDER by field created dynamicallyCakePHP 3 formatResults() 按动态创建的字段排序
【发布时间】:2015-06-22 07:42:50
【问题描述】:

我希望对我在formatResults() 中动态创建的字段进行排序

$users = $this->Users
->find('all')
->formatResults(function ($users) use ($lat, $lng) {
    return $users->map(function ($user) use ($lat, $lng) {
        $user->distance = getDist($lat, $lng);
        return $user;
    });
})
->order([
    'distance' => 'ASC'
]);

[...]

$this->set('users', $this->paginate($users));

字段$user->distance 不在数据库中。 $user->distance 包含一个浮点数 (getDist($lat, $lng);),它根据用户在请求时的位置而变化。

->order([
    'distance' => 'ASC'
]);

返回错误:Column not found: 1054 Unknown column 'Users.distance' in 'order clause'

我的问题是:我可以对我在接收用户信息时动态创建的字段进行排序吗?

【问题讨论】:

    标签: cakephp-3.0


    【解决方案1】:

    您可以按在 php 中计算的字段进行排序,但它不适用于分页,因为要进行排序,您需要数据库中的所有记录。您需要创建一个在 SQL 中运行的等效逻辑,以便进行排序。

    查看这个可以帮助您计算距离并按距离排序的插件https://github.com/dereuromark/cakephp-geo/

    这是find('distance') 自定义查找器,您可以在使用提供的行为时将其动态添加到表中。 https://github.com/dereuromark/cakephp-geo/blob/master/src/Model/Behavior/GeocoderBehavior.php#L223

    【讨论】:

    • 谢谢,我的函数'getDist()'是可操作的,所以我不需要插件,所以我会用MySQL研究一个替代品
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    相关资源
    最近更新 更多