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