ds34222222 2016-08-03 10:40
浏览 119
已采纳

如何在Laravel 5.2中使用paginate与关系?

I am trying to use paginate while selecting data from database by using relationships. I have three tables namely, users, contacts and contact_messages with models User, Contact, ContactMessage respectively.

I am trying to fetch all messages of a particular user by using the following method :

public function listMessage($user_id){
        $user1 = User::find($user_id);
        $messages = $user1->contact_messages;
        return View::make('message.listmessage')
        ->with('user_id', $user_id)
        ->with('messages', $messages);
    }

By this method I am getting all messages, but I couldn't paginate $messages . How can I paginate $messages? Can anyone help?

My models and relationships are given below :

class User extends Authenticatable
{
    public function contacts()
    {
        return $this->hasMany('App\Contact');
    }
    public function contact_messages()
    {
        return $this->hasManyThrough('App\ContactMessage', 'App\Contact');
    }
}

and Contact Model is

class Contact extends Model
{
    public function user(){
        return $this->belongsTo('App\User');
    }

    public function messages()
    {
        return $this->hasMany('App\ContactMessage');
    }
}

finally ContactMessage model is

class ContactMessage extends Model
{
    public function contact(){
        return $this->belongsTo('App\Contact');
    }
}
  • 写回答

1条回答 默认 最新

  • du3669 2016-08-03 10:47
    关注

    Try the following:

    $messages  = $user->contact_messages()->paginate(10);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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