【问题标题】:How to do an Eloquent query for a feed with a pivot table?如何使用数据透视表对提要进行 Eloquent 查询?
【发布时间】:2017-07-13 22:45:24
【问题描述】:

我有这个 laravel 应用程序 [实际上是 iPhone 应用程序的 API],我们有可以关注这个“类”或组的用户,并且在类中人们可以发布很多帖子,我的问题是如何进行查询对您拥有的所有课程的所有新帖子进行提要。

这是我的桌子:

用户

id - 姓名 - 电子邮件 - 密码

id - creators_id - 名称 - 描述

Classes_Users

user_id - clase_id

帖子

id - creators_id - clase_id - 标题 - 文本

型号:

        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');
    }

}

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    我想你要找的是Nested Eager Loading:

    $user = User->find($id)->with('clases.posts')->get();

    【讨论】:

    • 谢谢,但它给了我“消息”:“类 Illuminate\\Database\\Eloquent\\Builder 的对象无法转换为字符串”:( yahyazini
    • 非常感谢,但它会返回所有内容!有没有办法只加载帖子?我还需要按时间顺序排列它们,比如提要
    • 对于重新排序,您可以尝试: $user = User->find($id)->with('clases.posts')->get()->sortByDesc('clases.posts.created_at ');
    猜你喜欢
    • 2018-12-08
    • 2017-05-05
    • 2018-11-11
    • 2015-06-24
    • 2015-09-30
    • 2015-12-28
    • 2020-12-06
    • 1970-01-01
    相关资源
    最近更新 更多