1

我的数据库中有三个表。

帖子

作者

类别

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

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

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

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

一对一、一对多、多对多或多态

提前致谢。

4

2 回答 2

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;
于 2013-10-09T01:16:21.237 回答
-1

我做了这样的事情:

数据库表 =

用户 : 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;

它给出了一个空结果。

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

类用户扩展 SentryUserModel {

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

} 和

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

}
于 2013-11-01T20:35:27.463 回答