Reputation: 51
Guys I'm new to Laravel and I'm trying to find the name of the user that answers a certain question:
$users = User::with('answers')->where('question_id', $request->question_id)->get();
I've tried this but it doesn't work.It seems like he is trying to find the question_id
from the User and not from the Answer.
Answer Model
Class Answer extends Model{
public function users()
{
return $this->belongsTo(User::class);
}
}
User Model
Class User extends Authenticatable{
public function answers()
{
return $this->hasMany(Answer::class);
}
}
Upvotes: 0
Views: 8319
Reputation: 654
This is what you need, Constraining Eager Loads.
$users = User::with(['answers' => function ($query) use ($request) {
$query->where('question_id', $request->question_id)
}])->get();
Upvotes: 1
Reputation: 31832
This is not what you asked for but maybe what you need:
$answers = Answer::with('user')->where('question_id', $request->question_id)->get();
Upvotes: 0