使用Laravel和Eloquent选择正确的关系类型

时间:2013-10-09 00:24:13

标签: php laravel laravel-4 relationship eloquent

我的数据库中有三个表。

帖子

作者

分类

查看作者页面时,我希望能够查看作者的所有帖子以及帖子的类别。< / p>

在查看类别索引页面时,我希望能够查看该类别的所有帖子,还包括作者每个帖子。

查看帖子时,我希望能够包含类别作者

我可以用什么类型的关系来实现这个目标?

一对一,一对多,多对多,或多态

提前致谢。

2 个答案:

答案 0 :(得分:2)

您可以像这样创建关系:

class Post extends Eloquent {

    public funcion category()
    {
        return $this->belongsTo('Category');
    }

    public funcion author()
    {
        return $this->belongsTo('User');
    }

}

class Author extends Eloquent {

    public funcion posts()
    {
        return $this->hasMany('Post');
    }

}

class Category extends Eloquent {

    public funcion posts()
    {
        return $this->hasMany('Post');
    }

}

然后以这种方式使用它们:

$author = Author::find(1);

foreach($author->posts as $post)
{
    echo $post->title;
    echo $post->author->name;
}

$category = Category::find(1);

foreach($category->posts as $post)
{
    echo $post->title;
    echo $post->author->name;
}

$post = Post::find(1);

echo $post->category->title;
echo $post->author->name;

答案 1 :(得分:-1)

我做过这样的事情:

db table =

用户:id名称 辩论:id post user_id

现在在模特

class User extends SentryUserModel {


        public function debates()
    {
        return $this->hasMany('Debate', 'user_id');
    }
}

class Debate extends Eloquent {
    public function user()
    {
    return $this->belongsTo('User', 'id');
    }

}

现在在查询中

$debate= Debate::find(1);

echo $debates->user->name;
echo $debates->user->id;

它给出了一个null结果。

改变这两个解决问题。 (现在知道为什么我们不能在这里使用外键。如果有人知道这一点请告知)。

类用户扩展了SentryUserModel {

    public function debates()
{
    return $this->hasMany('Debate');
}

} 和

class Debate extends Eloquent {
    public function user()
    {
    return $this->belongsTo('User');
    }

}