Laravel雄辩的关系问题


laravel eloquent relationships issue

我有点困惑,我需要一些帮助,因为我在laravel新的!我有3张桌子!!问题、类别和主题

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

我要求做的是当我要添加一个问题时,我只从列表中选择一个类别,它将在问题表中添加与她对应的主题!!我希望我解释好了我的问题:)

the category migration 
Schema::create('category', function(Blueprint $table)
    {
        $table->increments('categoryId');
        $table->string('categoryName');
        $table->integer('themeId')->unsigned();
        $table->foreign('themeId')->references('themeId')->on('theme');
    });
the theme migration 
Schema::create('theme', function(Blueprint $table)
    {
        $table->increments('themeId');
        $table->string('themeName');
    });
the questio migration i didn't make relation since i didn't find a way to do it 
Schema::create('question', function(Blueprint $table)
        {
        $table->increments('questionId');
        $table->string('question', 200);
        $table->string('rightAnswer', 50);
        $table->string('explanation', 500);
        $table->string('wrongAnswer1', 50);
        $table->string('wrongAnswer2', 50);
        $table->string('wrongAnswer3', 50);
        $table->string('theme');
        $table->string('category');
        $table->integer('difficulty');
        $table->timestamps();
        });

主题模型

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');
    }
}

您不需要在迁移中创建Eloquent关系。迁移仅用于创建数据库表结构。相反,Eloquent中的关系是在您创建的模型中定义的:

// 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');
}

模型中的这些方法定义了Eloquent中的关系,并允许您做这样的事情:

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

话虽这么说,上面的方法在给定表结构的情况下不能精确地工作。Eloquent还依赖于约定,约定是外键应该以特定的方式命名,即theme_idcategory_id(而不是类别表中的themeId)。您可以使用以下格式在文档中重写此设置:

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
然后在您的Question模型中放置我上面概述的category方法。就这么简单。