Laravel Eloquent根据关系增加列

时间:2017-08-10 15:41:34

标签: php mysql laravel eloquent

我目前有一张图像链接表与另一个模型关联如下

+----+-------------+----------------+
| id | property_id |      url       |
+----+-------------+----------------+
|  1 |           2 | /example.jpg   |
|  2 |           7 | /example-2.jpg |
|  3 |           5 | /example-3.jpg |
+----+-------------+----------------+

我想在表格中添加一列来按如下顺序排列图像

+----+-------------+----------------+------------+
| id | property_id |      url       | sort_order |
+----+-------------+----------------+------------+
|  1 |           2 | /example.jpg   |          1 |
|  2 |           7 | /example-2.jpg |          1 |
|  3 |           2 | /example-3.jpg |          2 |
+----+-------------+----------------+------------+

是否有办法使数据库级别约束(即将其置于迁移中),sort_order值auto_increments但依赖于propery_id值,这样sort_order值本质上是一个索引,每个property_id都有它'自己的指数?

1 个答案:

答案 0 :(得分:2)

<table_name>应替换为您的表名。

关键在这一行

\DB::unprepared('CREATE TRIGGER <table_name>_sort_order BEFORE INSERT ON <table_name> FOR EACH ROW SET NEW.sort_order = (SELECT IFNULL(MAX(sort_order), 0) FROM <table_name> WHERE property_id = NEW.property_id) + 1;');

<?php

use Illuminate\Database\Migrations\Migration;

class AddSortOrderTo<table_name_camelized> extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table(<table_name>, function(Blueprint $table) {
            $table->unsignedInteger('sort_order')->default(0);
        });

        \DB::unprepared(\DB::unprepared('CREATE TRIGGER <table_name>_sort_order BEFORE INSERT ON <table_name> FOR EACH ROW SET NEW.sort_order = (SELECT IFNULL(MAX(sort_order), 0) FROM <table_name> WHERE property_id = NEW.property_id) + 1;');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        \DB::statement('DROP TRIGGER <table_name>_sort_order');

        Schema::table(<table_name>, function (Blueprint $table) {
            $table->dropColumn('sort_order');
        });
    }
}