laravel 4表之间雄辩的关系

时间:2018-02-14 02:58:29

标签: laravel

我有四张表post user_post user_infousers

在这里,我给出了四个我想用滔滔不绝的查询。

表示post表:(型号:post

$post_id = select id from post

代表user_post(型号:Userpost

$student_id = select student_id from user_post where post_id = $post_id

表示user_info表:(型号:userInfo

$user_id = select user_id from user_info where student_id = $student_id

表示user表:(型号:user_table

$student_name = select name from user where $student_id = $user_id

最后打印这个$ student_name。 我想做的是, 一个帖子可以有很多学生。我想打印那些学生名字。

3 个答案:

答案 0 :(得分:1)

将这些现实添加到Post模型以获取用户和user_post

//post has one user post
public function userPost(){
    return $this->hasOne('App\Userpost','post_id','id');
}


//post has many users
public function users(){
    return $this->hasMany('App\user_table','user_id','student_id');
}

答案 1 :(得分:0)

Post模型的关系添加到用户:

public function users() {
      return $this->hasMany(User::class, 'student_id');
}

然后查询用户:

$posts = Post::with('users')->get();
$names = $posts->users->pluck('name');

答案 2 :(得分:0)

尝试嵌套预先加载

//Post Model
public function user_post (){
     $this->belongTo('user_post');
}

//user_post model
public function user_info(){
     $this->belongTo('user_info');
}

//user_post model
public function user(){
     $this->belongTo('user');
}



On your controller
Post::with('user_post.user_info.user')->where('id',$post_id)->get();

希望有帮助