Reputation: 7688
I am trying to get all questions, by category, where the author of the question is Y
.
This is how I am trying to do so:
QuestionCategory::with('questions')->where('questions.source', '=', $userId)->get();
The problem is that, it does not apply the where to questions
table, but to question_categories
one.
Column not found: 1054 Unknown column 'questions.source' in 'where clause' (SQL: select * from
question_categories
wherequestions
.source
= 2)
Any idea what am I missing?
Upvotes: 2
Views: 4496
Reputation: 2757
May be you should see the relationship system of laravel. In your model you can specify a relation between two tables.
Class User Extends Eloquent {
public function questions()
{
return $this->hasMany('Your Model Question name', 'userid column name in questions table', 'userid column name in users table')
}
}
Then to access to that relation
$user = User::find('tape an userid');
$questionsByUser = $user->questions;
I'm not sure that's what you ask but that's gonna give you an instance with all questions owned by an user.
Upvotes: 1
Reputation: 33148
If you are looking to limit based on a relationship, you will have to structure your code a bit differently. This should work for you...
QuestionCategory::with(array('questions' => function($q) use ($userID)
{
$q->where('source', '=', $userID);
}))->get();
Please note though that this does not limit the QuestionCategory
as they will all still be grabbed. If a QuestionCategory
doesn't have a source with that user id associated with it, it will still grab that QuestionCategory
.
If you want only QuestionCategories that have a source with that user id, you may use the whereHas()
function.
$categories = QuestionCategory::whereHas('permissions', function($q)
{
$q->where('name', '=', 'CreateUser');
})->get();
Upvotes: 1
Reputation: 1064
The questions table is eager loaded in a separate query, so your where statement doesn't have access to the questions table.
You'll have to join it in order to query it.
QuestionCategory::with('questions')
->join('questions', 'question_id', '=', 'questions.id')
->where('questions.source', '=', $userId)
->get();
Upvotes: 2