laravel雄辩的关系问题

时间:2014-08-25 10:48:57

标签: php mysql laravel eloquent relationship

我有点困惑,我需要一些帮助,因为我是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();
        });

2 个答案:

答案 0 :(得分:0)

主题模型

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

答案 1 :(得分:0)

您不会在迁移中建立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(vs themeId,就像在类别表中一样)。您可以使用以下格式按documentation覆盖此内容:

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

然后在您的问题模型中放置我在上面概述的category方法。就这么简单。