Reputation: 8519
I'm new to Laravel and I'm stuck. This is what I am struggling with:
$questions = Question::find($id)->quiz(); // this code retrieves data from
// the table using the primary key
// in the table. The is a parameter
// that is passed via get.
This is what I have right now:
$questions = Question::where('quiz_id', '=', $id)->quiz();
This is the error I get:
Call to undefined method Illuminate\Database\Query\Builder::quiz()
What I want to do:
I want to run a query to get data from my database table using the foreign key in the table not the primary key, I also want to be able to use relations with this as seen from what I tried to do above.
Edit: Added the Question Model
<?php
class Question extends Eloquent{
protected $table = 'quiz_questions';
public function quiz()
{
return $this->belongsTo('Quiz');
}
}
Upvotes: 0
Views: 105
Reputation: 2520
Wader is correct, just calling where()
will not execute your query. You either call get()
and get an iterable result or use first()
if you only want one result.
$quiz = Question::where('quiz_id', '=', $id)->first()->quiz();
Upvotes: 1
Reputation: 9868
Calling the quiz() function from Question::find($id)->quiz()
will return a Query Builder instance allowing you to query the parent of the Question, its not going to return any data at that point until you call ->get()
or another method that actually executes the query.
If you're wanting to return all the questions belonging to a certain quiz then you can do it like this.
$questions = Question::where('quiz_id', $id)->get();
This will return an Eloquent\Collection
of the results for all questions with a quiz_id
that is equal to $id
.
If you've setup the relations between the Quiz and Questions then you can also do this using the Laravel relations.
$quiz = Quiz::findOrFail($id);
foreach($quiz->questions as $question)
{
// Do stuff with $question
}
Laravel will automagically pull Questions from the database that belongTo the Quiz you've already got from the database, this is known as eager loading http://laravel.com/docs/4.2/eloquent#eager-loading
Upvotes: 1