php - laravel Eloquent 关系问题

标签 php mysql laravel eloquent relationship

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

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

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

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

关于php - laravel Eloquent 关系问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25484232/

相关文章:

mysql - 使用docker进行单元测试

php - 从 MySQL/PHP 获取嵌套/分层 JSON

web-services - 在 laravel/lumen 中使用客户端 ID 和 key 访问 API

外键中的 Laravel 整数 v biginteger

php - 如何获取 OpenID 用户个人资料信息?

php - 根据常见日期循环遍历 MySQL 数据

javascript - 如何在脚本部分中使用我的 php 代码部分中的变量?

PHP if 语句。如果为真则显示和图像

MySQL 表中的最新记录

php - 一个包含许多基于链接的数据库的 laravel 文件夹