【问题标题】:How to sort a array with objects foreign key value must be first (Laravel)如何对具有对象外键值的数组进行排序必须是第一个(Laravel)
【发布时间】:2020-08-11 01:13:54
【问题描述】:

我正在尝试对 Laravel 中的对象数组进行排序,我将帖子 categorie_id 的当前外键值设置为数组中的第一位。

之后,其他对象需要按降序过滤。

代码:

$categorie = Categorie::all()->sortBy($posts->categorie_id);

这并不完全有效,数组保持不变。 在这种情况下,我的 VIEW 有一个外键为 4 的帖子

【问题讨论】:

  • 不清楚你的意思

标签: php arrays laravel sorting object


【解决方案1】:
$categorie = Categorie::with(['posts' => function ($q) {
  $q->orderBy('categorie_id', 'desc');
}])->find($categorie_id);

// when lazy loading
$categorie = Categorie::find($categorie_id);
$categorie->load(['posts' => function ($q) {
  $q->orderBy('categorie_id', 'desc');
}]);

// or on the collection
$categorie = Categorie::find($categorie_id);
$categorie->posts->sortByDesc('categorie_id');


// or querying students directly
$categorie = Categorie::whereHas('posts', function ($q) use ($categorie_id) {
  $q->where('id', $categorie_id);
})->orderBy('categorie_id')->get();

【讨论】:

  • 这给了我:asort() 期望参数 2 是 int,给定字符串
  • categorie_id 来自表“posts”,表posts不知道这个
  • @SebastianTramper 所以类别有很多帖子,你想按帖子的 categorie_id 对类别进行排序?
猜你喜欢
  • 2021-02-15
  • 1970-01-01
  • 2021-11-23
  • 1970-01-01
  • 2012-02-08
  • 2018-10-29
  • 1970-01-01
  • 2017-10-17
  • 2017-12-02
相关资源
最近更新 更多