duangang79177 2013-11-09 10:34
浏览 23

检索用户帖子和朋友发帖

I have four eloquent models for four tables; Users, Profiles, Habs, Followers. I am trying to retrieve all user posts and posts of users a user follower. My tables looked like this;

Habs

  • id
  • user_id
  • hab
  • created_at
  • updated_at

Users

  • id
  • username
  • email
  • created_at
  • updated_at

Profiles

  • id
  • user_id
  • name
  • avatar
  • created_at
  • updated_at

Followers

  • id
  • follower_id
  • following_id
  • created_at
  • updated_at

    I have set up the relationships in models. How do use the Eloquent to select user posts and posts of users the user follows.

  • 写回答

3条回答 默认 最新

  • dtdvlazd56637 2013-11-09 11:13
    关注

    Well, I think you can start with something like this:

    class Users extends Eloquent {
    
        protected $table = 'users';
    
        public function profile()
        {
            return $this->belongsTo('Profile');
        }
    
        public function followers()
        {
            return $this->hasMany('Follower', 'follower_id', 'id');
        }
    
        public function following()
        {
            return $this->hasMany('Follower', 'following_id', 'id');
        }
    
    }
    
    class Hab extends Eloquent {
    
        protected $table = 'habs';
    
        public function user()
        {
            return $this->belongsTo('User');
        }
    
    }
    
    class Follower extends Eloquent {
    
        protected $table = 'followers';
    
    }
    
    class Profile extends Eloquent {
    
        protected $table = 'profiles';
    
    }
    

    And you should be able to:

    Select a user normally

    $user = User::find(1);
    

    Get its Habs

    $habs = $user->habs;
    

    Get its followers

    $followers = $user->followers;
    

    Get who are following him/her

    $following = $user->following;
    

    Get all habs of their Followers

    foreach($user->followers as $follower)
    {
    
        $followerEmail = $follower->email;
        $followerName = $follower->profile->name;
        $followerHabs = $follower->habs;
    
    }
    

    Get all habs from people he/she is following

    foreach($user->following as $following)
    {
    
        $followingEmail = $following->email;
        $followingName = $following->profile->name;
        $followingHabs = $following->habs;
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 python变量和列表之间的相互影响
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)