0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

方法

  1. DBからクエリビルダで->toArrayを用いて配列で取得
  2. usortでソートし直す
// Post(オブジェクト)の配列を、Post(配列)の配列に変換する
$posts = $user->posts->toArray();
// 第1引数にPostの配列を、第2引数に$a、$b(を
// 引数に持つコールバックを渡す
usort($posts, function ($a, $b) {
    if ($a['updated_at'] != $b['updated_at']) {
        // 両者のupdated_atが異なる、つまり比較が可能
        return ($a['updated_at'] < $b['updated_at']) ? +1 : -1;
    }

    if ($a['created_at'] != $b['created_at']) {
        return ($a['created_at'] < $b['created_at']) ? +1 : -1;
    }

    // 両者のupdated_at、created_atが同じ場合、idで比較
    return ($a['id'] < $b['id']) ? +1 : -1;
});

参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?