Mike Rinehart
Mike Rinehart

Reputation: 445

Trouble Retrieving Proper Results with Laravel Eloquent Relations

I'm having trouble retrieving a certain set of results with my Eloquent relations.

Models:
Application(table: application) [id, title, active]
Question(table: question) [id, application_id, question_text, helper_text, question_type]
QuestionType(table: question_type) [id, type]
Bold = primary key, italic = foreign key

Relationships:
One Application has many Questions.
Many Questions can belong to one Application.

One Question has one QuestionType (referenced by question_type FK)
One QuestionType can belong to many Questions (by referencing it's id as a question_type)

QuestionType is a static table that will never have values added or removed, however the type attributes can change.

I would like to be able do something like this:

$application = Application:find($application_id);  
$questions = $application->questions()->get();

and have that replace question_type with the appropriate type pulled from the QuestionType model.

I have look through the Laravel and Eloquent docs, asked on IRC, and looked through other StackOverflow articles, yet could not find an answer that helped. I think what is throwing me off is my unconventional foreign key, question_type, in my Question table. I got it to KIND OF work once, exception question_type was being replaced with an QuestionType array (which won't work).

Upvotes: 1

Views: 89

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152860

Id say first add this relationship to Question:

public function type(){
   return $this->belongsTo('QuestionType', 'question_type');
}

Then just use it like normal:

$question = Question::find(1);
$question->type;

And for all questions of an application (with eager loading)

$application = Application:find($application_id);  
$questions = $application->questions()->with('type')->get();

Edit

To get only the actual name of the type (column named type) you can add an attribute accessor. However with that the naming gets a bit more difficult. If you really don't want to change your foreign key name to question_type_id I suggest this:

public function typeRelation(){
    return $this->belongsTo('QuestionType', 'question_type');
}

public function getTypeAttribute(){
    if(is_null($this->typeRelation)) return null;
    return $this->typeRelation->type;
}

The attribute accessor allows you to use $question->type and get the attribute of the related model directly. Don't forget to adjust the relation name when eager loading: with('typeRelation')

Upvotes: 2

Related Questions