Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel hasMany relationship not working properly

i am new to Laravel model relationships, and i am trying to learn it by building a basic forum system. I am trying to have the fourms belong to the forums 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';
}

Here is how I try to test it:

$category=ForumCategory::find(1);
print_r($category->forums());

But what i get from the print_r is a very large object, and not the related forums.

Thank you.

like image 548
user3460046 Avatar asked Dec 11 '25 01:12

user3460046


1 Answers

What you want is the Eloquent's dynamic 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 what you currently have is the QueryBuilder.

More on this here: http://laravel.com/docs/eloquent#querying-relations

like image 152
JofryHS Avatar answered Dec 13 '25 15:12

JofryHS