Laravel hasMany relationships don't work as expected
I'm new to Laravel model relationships and I'm trying to learn it by building a basic forum system. I'm trying to get the fours to belong to the forum categories:
Here is my ForumCategory model:
class ForumCategory extends Eloquent {
protected $table = 'forum_categories';
public function forums()
{
return $this->hasMany('Forum','category_id');
}
}
The forum model name is forum and the foreign key is category_id.
Here is the forum model:
class Forum extends Eloquent {
protected $table = 'forums';
}
This is how I try to test it:
$category=ForumCategory::find(1);
print_r($category->forums());
But what I get from print_r is a very large object, not related forums.
Thank.
+3
source to share
1 answer
What you want is a dynamic Eloquent property when calling the relationship.
To illustrate:
// Return you chainable queries
$query = ForumCategory::find(1)-> forums()->...
// To actually return the forums
// You need to use get() since it is a chainable query builder
$query = ForumCategory::find(1)-> forums()->get();
// BUT, you can use Eloquent dynamic property
// Notice no '()'
// Return you collection of forums
$patientsCollection = ForumCategory::find(1)-> forums;
Essentially, you have a QueryBuilder.
More on this here: http://laravel.com/docs/eloquent#querying-relations
+5
source to share