Php 拉威尔雄辩的人际关系问题

Php 拉威尔雄辩的人际关系问题,php,mysql,laravel,eloquent,relationship,Php,Mysql,Laravel,Eloquent,Relationship,我有点困惑,我需要一些帮助,因为我是新来的拉雷维尔! 我有三张桌子!!问题、类别和主题 问题有类别和主题 一个主题有很多类别 一个类别属于一个主题 我要做的是,当我添加一个问题时,我只从列表中选择一个类别,它将与她相应的主题一起添加到问题表中!!我希望我能很好地解释我的问题:) 主题模型 class Theme extends Eloquent { protected $primaryKey = 'themeId'; protected $guarded = array(

我有点困惑,我需要一些帮助,因为我是新来的拉雷维尔! 我有三张桌子!!问题、类别和主题

问题有类别和主题 一个主题有很多类别 一个类别属于一个主题

我要做的是,当我添加一个问题时,我只从列表中选择一个类别,它将与她相应的主题一起添加到问题表中!!我希望我能很好地解释我的问题:)

主题模型

class Theme extends Eloquent 
{   
    protected $primaryKey = 'themeId';
    protected $guarded = array();
    public function category()
    {
        return $this->hasMany('Category');
    }
}
类别模型

class Category extends Eloquent 
{
    protected $primaryKey = 'categoryId';

    protected $guarded = array();

    public function theme()
    {
        return $this->belongsTo('Theme');
    }
}
问题模型

class Question extends Eloquent 
{
    protected $primaryKey = 'questionId';

    protected $guarded = array();

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

你在迁移中没有建立起雄辩的关系。迁移仅用于创建数据库表结构。相反,Elount中的关系是在您制作的模型中定义的:

// Theme Model
public function categories()
{
    return $this->hasMany('Category');
}

//  Category Model
public function theme()
{
    return $this->belongsTo('Theme');
}

public function questions()
{
    return $this->hasMany('Question');
}

// Question Model
public function category()
{
    return $this->belongsTo('Category');
}
模型中的这些方法以雄辩的方式定义关系,并允许您执行以下操作:

// Given an instance of a theme
foreach($theme->categories as $category)
    // ...

// Given an instance of a question
echo $question->category->theme->themeName;
也就是说,鉴于您的表结构,上述方法将无法精确地工作。Eloquent还依赖于约定,约定是外键应以特定的方式命名,即
theme\u id
category\u id
(vs
themeId
,就像您在categories表中一样)。您可以使用以下格式根据覆盖此内容:

return $this->belongsTo('Theme', 'themeId');
虽然你最好还是坚持传统。该约定还规定每个表的主键应命名为
id

对于问题表,您可以创建与类别的关系,与主题和类别之间的关系相同:在问题表中添加一列引用类别id:

// Your migration:
$table->integer('category_id');
// Add a foreign key as well if you wish, though it is not 
// required for the relationship in Eloquent
然后在您的问题模型中放置我上面概述的
类别
方法。就这么简单

// Your migration:
$table->integer('category_id');
// Add a foreign key as well if you wish, though it is not 
// required for the relationship in Eloquent