dongna9185 2017-03-11 10:08
浏览 86
已采纳

检索两个模型并按日期排序

I'm trying to retrive the 20 most recent elements from two differents models Post and Link and rank them by the field created_at in descending order.

Here is the link class

class Link extends \Illuminate\Database\Eloquent\Model {
  public $incrementing = false;

  public function author() {
    return $this->belongsTo('App\Models\Author');
  }

  public function category() {
    return $this->belongsTo('App\Models\Category');
  }
}

And here the post class

class Post extends \Illuminate\Database\Eloquent\Model {
  public $incrementing = false;

  public function author() {
    return $this->belongsTo('App\Models\Author');
  }

  public function category() {
    return $this->belongsTo('App\Models\Category');
  }
}

How can I do that with eloquent (I'm using it outside Laravel, with Slim)?

  • 写回答

2条回答 默认 最新

  • dpiw16824 2017-03-12 09:38
    关注

    The merge method was the answer :

    $posts = \App\Models\Post::where('draft', false)->orderBy('created_at', 'desc')->take(20)->get();
    $links = \App\Models\Link::orderBy('created_at', 'desc')->take(20)->get();
    
    $result = $posts->merge($links)->sortByDesc('created_at')->take(20);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器