drnf09037160 2015-01-06 23:17
浏览 44
已采纳

laravel ORM多个值

I'm working on learning a bit about laravel, and I'm a little unsure of what the proper route is for the following:

I want to have a user dashboard that shows the user's total messages, divided up by the read / unread messages, as well as a task list showing upcoming tasks as well as overdue tasks.

Right now the way I'm looking at doing this is setting these values in the controller:

// the user index controller function
public function getIndex()
{
    $read = Message::where('user_id', '=', Auth::user()->id)
            ->where('read', '=', 1);
    $unread = Message::where('user_id', '=', Auth::user()->id)
            ->where('read', '=', 0);
    // etc

    return View::make('user.index');
}

This seems really a bit pointless and repetitive. Is there a way to return the total messages result to the view and then split them up by read / unread there, or is it smarter to create functions in the model that will return these number directly? Or maybe I'm totally missing the right way?

Thanks

  • 写回答

3条回答 默认 最新

  • dongyi8795 2015-01-07 16:12
    关注

    The most convenient way would be creating simple relations:

    // User
    public function messages()
    {
      return $this->hasMany('Message');
    }
    
    public function unreadMessages()
    {
      return $this->messages()->where('read', 0);
    }
    
    // or using filter method and accessor
    public function getUnreadMessagesAttribute()
    {
      return $this->messages->filter(function ($message) {
         return $message->read == 0;
      });
    }
    
    public function readMessages()
    {
      return $this->messages()->where('read', 1);
    }
    
    public function tasks()
    {
      return $this->hasMany('Task');
    }
    
    public function todoTasks()
    {
      // for example:
      return $this->tasks()->where('deadline', '>', Carbon::now())->where('done', 0);
    }
    
    public function overdueTasks()
    {
      return $this->tasks()->where('deadline', '<', Carbon::now())->where('done', 0);
    }
    

    Then you can simply use this:

    Auth::user()->overdueTasks;
    Auth::user()->unreadMessages;
    

    2nd solution using filter on the collection has one advantage = it saves the DB query.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题