【问题标题】:Laravel 5 orderby one-to-one relationLaravel 5 orderby 一对一关系
【发布时间】:2015-12-29 07:56:11
【问题描述】:

我在使用 Laravel 5.1 和 Eloquent 时遇到了一个非常基本的问题。

为了简单起见,我减少了这个例子的问题:我有 2 个模型:

线索:

ID  |  name  |  fk_city

城市:

ID  |  name  |  postalcode

在 Leads.php 模型中:

public function city() {
    return $this->belongsTo('\App\Models\Cities','fk_city');
}

我想根据城市名称对线索进行排序。

我已经尝试了 eagger load orderby :

Leads::with(['city'=>function($q) {
    $q->orderby('name','desc');
}])->get();

但不影响结果。

我还读到我们必须使用“join()”语句并手动告诉 Eloquent 做什么。这似乎有点矫枉过正,因为这种类型是任何 ORM 都必须具备的基本功能。

感谢您的想法:)

【问题讨论】:

    标签: php sql laravel eloquent


    【解决方案1】:

    Eloquent 遵循 Active Record 模式,因此通常使用单独的查询进行预先加载。为此,您需要加入:

    Leads::join('cities', 'leads.fk_city', '=', 'cities.ID')->orderby('cities.name','desc')->with('city')->get();
    

    如果您经常需要这种查询,您可以create an scope in your model 重复使用该查询。

    其他选项是,由于您的结果是 Laravel 集合,您可以使用集合对象的方法 sortBy() or sortByDesc()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 2017-03-25
      • 2013-08-11
      • 2015-07-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      相关资源
      最近更新 更多