drnf09037160 2015-01-06 15: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 08: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部