简体   繁体   English

Laravel有很多关系不能正常工作

[英]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. 我是Laravel模型关系的新手,我正在尝试通过构建一个基本的论坛系统来学习它。 I am trying to have the fourms belong to the forums categories: 我试图将fourms属于论坛类别:

Here is my ForumCategory model: 这是我的ForumCategory模型:

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. 论坛模型名称为Forum,外键为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. 但是我从print_r获得的是一个非常大的对象,而不是相关的论坛。

Thank you. 谢谢。

What you want is the Eloquent's dynamic property, when calling the relationship. 在调用这种关系时,你想要的是Eloquent的动态属性。

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. 基本上你现在拥有的是QueryBuilder。

More on this here: http://laravel.com/docs/eloquent#querying-relations 更多相关内容: http//laravel.com/docs/eloquent#querying-relations

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM