Reputation: 854
I have four tables post
user_post
user_info
and users
.
Here I am giving four query that I want to do with eloquent.
for post
table: (Model: post
)
$post_id = select id from post
for user_post
(Model: Userpost
)
$student_id = select student_id from user_post where post_id = $post_id
for user_info
table:(Model: userInfo
)
$user_id = select user_id from user_info where student_id = $student_id
for user
table:(Model: user_table
)
$student_name = select name from user where $student_id = $user_id
and finally print this $student_name. What I want to do is, One single post can have many student. I want to print those student name.
Upvotes: 1
Views: 720
Reputation: 108
Try Nested Eager Loading
//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();
Hope that help
Upvotes: 0
Reputation: 633
Add these realtions to Post model to get users and 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');
}
Upvotes: 1
Reputation:
Add a relation on the Post
model to users:
public function users() {
return $this->hasMany(User::class, 'student_id');
}
Then query for users like:
$posts = Post::with('users')->get();
$names = $posts->users->pluck('name');
Upvotes: 0