Latest

Thursday, July 13, 2017

How to do an Eloquent query for a feed with a pivot table?

Asked by: Juan Carlos Estevez Rodriguez


I have this laravel app [is actually an API for an iPhone app] where we have users that can follow this "Clases" or groups and inside the clases people can make many posts, my question is how to do a query to make a feed of all the new posts around all the clases that you have.

this are my tables:

Users

id - name - email - password

Clases

id - creators_id - name - description

Clases_Users

user_id - clase_id

Posts

id - creators_id - clase_id - title - text

Models:

        class User extends Authenticatable
    {
        use Notifiable;

        use SoftDeletes;

        /**
         * The attributes that should be mutated to dates.
         *
         * @var array
         */
        protected $dates = ['deleted_at'];

        protected $primaryKey = 'id';

        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
            'name', 'email', 'password','about'
        ];

        /**
         * The attributes that should be hidden for arrays.
         *
         * @var array
         */
        protected $hidden = [
            'password', 'remember_token',
        ];

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

        public function clases(){
            return $this->belongsToMany('App\Clase','clase_user', 'user_id');
        }

        public function claseAdmin(){
            return $this->hasMany('App\Clase');
        }
    }
class Clase extends Model
{
    protected $fillable = [
        'users_id', 'descripcion', 'name', 'tema_id',
    ];

    public function Tema(){
        return $this->hasOne('App\Temas');
    }

    public function User(){
        return $this->hasOne('App\User');
    }

    public function posts(){

        return $this->hasMany('App\Posts');

    }


}
class Posts extends Model
{
    protected $fillable = [
        'users_id', 'clase_id', 'text', 'archivo',
    ];

    public function Clase(){
        return $this->hasOne('App\Clase');
    }

}


Source

No comments:

Post a Comment

Adbox