【发布时间】:2020-05-11 14:42:52
【问题描述】:
我的 Laravel 5.8 项目中有两个模型,两个模型类中的关系如下所示。如何使用单个 sql 查询获取与我关注的每个用户相关的每个帖子记录?我可以使用 Eloquent Query Builder 还是我需要 Raw SQL Query 来获得它?有人可以告诉我执行此操作的 SQL 查询吗?
抱歉,我不知道该问题的标题。
提前致谢!
用户类。
class User extends Authenticatable implements MustVerifyEmail{
use Notifiable, MessageAccessible, TagsCreator;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
"lastname",
"country",
"city",
"phone_number",
'e_mail',
'password',
"role_id",
"profile_picture",
"occupation",
"biography"
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token'
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = ['email_verified_at' => 'datetime'];
public function posts(){
return $this->hasMany(Post::class);
}
public function followers(){
return $this->belongsToMany(User::class, 'follower_followed', 'followed_id', 'follower_id');
}
public function following(){
return $this->belongsToMany(User::class, 'follower_followed', 'follower_id', 'followed_id');
}
}
发布类。
class Post extends Model{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'user_id',
"post_permission_id",
"title",
"content",
"likes",
"dislikes"
];
public function user(){
return $this->belongsTo(User::class);
}
}
【问题讨论】:
标签: sql laravel eloquent laravel-5.8 laravel-query-builder