【问题标题】:Laravel orderBy hasMany RelationshipLaravel orderBy hasMany 关系
【发布时间】:2016-03-02 12:59:56
【问题描述】:

我的下一个问题是订购具有 hasMany 关系且订购字段在关系中的项目。

我有表:国家,它只有 ID 字段 我还有表:country_translation,其中有列:名称、语言

在我的 CountryController 中的 index() 方法中,我想显示默认语言的所有国家/地区,按参数名称对它们进行排序并对其进行分页。

这是我的国家模型:

class Country extends Model {

    protected $fillable = [
        'code', 'latitude', 'longitude', 'currency_id', 'timezone', 'dam_date', 'status',
    ];

    public function translations() {

        return $this->hasMany('App\Models\CountryTranslation');

    }
}

国家翻译模型:

class CountryTranslation extends Model {

    protected $fillable = [
        'name', 'lang', 'country_id',
    ];

    public function country() {
        return $this->hasOne('Country');
    }
}

【问题讨论】:

    标签: php laravel relationship


    【解决方案1】:

    如果我没猜错,这应该可行:

    $countries = CountryTranslation::where('lang', 'en')->orderBy('name')->paginate(20)
    

    【讨论】:

      猜你喜欢
      • 2020-03-25
      • 2021-07-01
      • 2013-08-11
      • 2019-03-04
      • 2021-12-14
      • 2021-03-22
      • 2021-09-24
      • 2016-03-17
      • 1970-01-01
      相关资源
      最近更新 更多