【问题标题】:Multi table inheritance in LaravelLaravel 中的多表继承
【发布时间】:2016-11-03 15:25:52
【问题描述】:

我想要一个简单的例子,说明如何使用 Eloquent 在数据库中创建多个表,例如: 我有一个模型“人”,并且从这个模型扩展了 2 个类:学生和教师,在数据库中我不想有一张表(人),我想要两张表(学生和教师)。

这在 Laravel (Eloquent) 中是如何实现的,请给我三个类(Person、Student 和 Teacher)的代码。

非常感谢:)

【问题讨论】:

    标签: laravel inheritance eloquent


    【解决方案1】:

    未经测试但应该可以工作:

    Docs

    Person.php

    <?php 
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Person extends Model {
        // ...
    }
    

    Student.php

    <?php 
    namespace App;
    class Student extends Person {
        $table = 'students';
        // ...
    }
    

    Teacher.php

    <?php 
    namespace App;
    class Teacher extends Person {
        $table = 'teachers';
        // ...
    }
    

    迁移

    您可以像往常一样使用php artisan make:migration create_students_table --create=students 创建所需的迁移。然后使用php artisan migrate迁移

    <?php
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;
    
    class CreateStudentsTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('students', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                // ...
                $table->timestamps();
                $table->softDeletes();
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('students');
        }
    }
    

    编辑

    我不知道背景,但也许特质是更好的选择。

    【讨论】:

    • 谢谢 我不知道 $table 变量,这很有帮助。但是这个模型的迁移文件呢,因为当我执行命令 php artisan migrate 时,表教师和学生不包含任何列!
    • 你必须像往常一样定义你的迁移文件..检查迁移编辑
    • 如果我要定义迁移文件中的所有列,那么Person和Student之间继承的目的是什么?
    • 我不知道你的应用程序/结构 - 可能是不同的方法、关系和东西。你也可以使用同一张桌子?!我会推荐给normalize
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多