2017-08-10 78 views
3

我現在有圖像鏈接關聯的表與其他型號的列如下Laravel雄辯增加基於關係

+----+-------------+----------------+ 
| 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 | 
+----+-------------+----------------+------------+ 

有沒有辦法讓一個數據庫級別的約束(即把它的遷移)的排序順序值auto_increments而是取決於propery_id值,使得SORT_ORDER值基本上每個PROPERTY_ID有它的索引自己的索引?

回答

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