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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?