【问题标题】:Laravel Eloquent model : 2field, one fk refer 2 fields on other tableLaravel Eloquent 模型:2 个字段,一个 fk 引用另一个表上的 2 个字段
【发布时间】:2019-08-10 19:08:27
【问题描述】:

我想使用 Laravel Eloquent 模型和关系来连接我项目中所有表的数据;但是,我在翻译这些关系时遇到了问题。例如,我有两张桌子;第一个是 Books 表,另一个是 Author 表。

Schema::create('books', function (Blueprint $table) {
    $table->increments('id');
    $table->string('code', 20)->unique('ak_books__code')->nullable(false);
    $table->smallInteger('books_type_id');
    $table->float('detection_limit', 10, 0);
    $table->smallInteger('books_classification_id');
    $table->smallInteger('books_number');
    $table->foreign(['books_classification_id', 'books_number'], 'fk_books__classification_scales')
        ->references(['calibration_id', 'number'])->on('classification')
        ->onUpdate('RESTRICT')->onDelete('RESTRICT');
});

Schema::create('classification', function (Blueprint $table) {
    $table->smallInteger('calibration_id');
    $table->smallInteger('number');
    $table->string('name', 50);
    $table->primary(['calibration_id', 'number'], 'pk_classification_scales');
    $table->foreign('calibration_id', 'fk_classification_calibration')->references('id')
        ->on('calibration_parameters')->onUpdate('CASCADE')->onDelete('CASCADE');
});

如何在 Books 表上建立关系以获取 numbercalibration_id

【问题讨论】:

标签: laravel eloquent relationship laravel-5.8


【解决方案1】:

和书籍分类一样,我将向您展示一个关于任务-项目之间关系的示例(这个任务的项目是什么):

任务

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('tasks', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->text('description');
        $table->string('name');
        $table->integer('project_id')->unsigned();
        $table->timestamp('start_date');
        $table->timestamp('end_date');
        $table->timestamps();

        $table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade')->onUpdate('cascade');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('tasks');
}

项目

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('projects', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('description');
        $table->tinyInteger('active')->default(1);
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('projects');
}

希望对你有帮助,问候!

【讨论】:

  • 您好,感谢您的帮助,但在您的示例中,您没有复合外键:这是我的问题。我可以使用复合外键,我认为 laravel eloquent 不能使用它:S
  • 啊好吧!我没有很好地理解你。看看这个链接:stackoverflow.com/questions/39736866/…
猜你喜欢
  • 2020-06-03
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 2011-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多