我有这个laravel应用程序[实际上是一个iPhone应用程序的API]我们有用户可以关注这个“Clases”或组,并且在clases中人们可以发很多帖子,我的问题是如何进行查询围绕你拥有的所有文章提供所有新帖子的摘要。
这是我的表格:
用户
id - name - email - password
Clases
id - creators_id - 名称 - 描述
Clases_Users
user_id - clase_id
帖子
id - creators_id - clase_id - title - text
型号:
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');
}
}
答案 0 :(得分:0)
我认为你要找的是Nested Eager Loading:
$user = User->find($id)->with('clases.posts')->get();