私は2つのテーブルを持っていますroutes
し、stations
そして1つのピボットテーブルroute_station
。テーブルの詳細を参照してください。
ルートテーブル
id, number, code
ステーションテーブル
id, name, code
route_stationテーブル(ピボット)
id, route_id, station_id, next_station_id, interchange_station_id, sation_order, distance, duration
station_id
、next_station_id
、interchange_station_id
すべてのあるsatations
テーブルID
スキーマ
駅
Schema::create(
'stations',
function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->index();
$table->string('code')->index();
$table->text('info');
$table->string('photo')->nullable();
$table->timestamps();
}
);
ルート
Schema::create(
'routes',
function (Blueprint $table) {
$table->bigIncrements('id');
$table->smallInteger('number')->unsigned()->unique();
$table->string('code')->unique();
$table->timestamps();
$table->unique(['number', 'code'], 'routes_unique_columns');
}
);
Route_Station - ピボット
Schema::create(
'route_station',
function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('route_id')->unsigned();
$table->bigInteger('station_id')->unsigned();
$table->bigInteger('next_station_id')->unsigned()->nullable();
$table->bigInteger('interchange_id')->unsigned()->nullable();
$table->integer('station_order');
$table->float('distance');
$table->integer('duration');
$table->timestamps();
$table->foreign('route_id')
->references('id')
->on('routes')
->onDelete('restrict');
$table->foreign('station_id')
->references('id')
->on('stations')
->onDelete('restrict');
$table->foreign('next_station_id')
->references('id')
->on('stations')
->onDelete('restrict');
$table->foreign('interchange_id')
->references('id')
->on('routes')
->onDelete('restrict');
}
);
管理エリアでは、駅やルートを管理するために、3つのセクションの合計があるでしょう。
- 駅ページ
- ルートページ
- 私はルートにステーションを追加することができます
作成中ということを意味私は、ピボットにレコードを挿入するつもりはありませんstation
かをroute
上記第三ページの記載から、後が、いつでも。
私は今、二つのモデルを持っているStation
とRoute
し、以下のような関係を設定します。
駅モデル
class Station extends Model
{
public function routes()
{
return $this->belongsToMany('App\Route');
}
public function route()
{
return $this->belongsTo('App\Route');
}
}
ルートモデル
class Route extends Model
{
public function stations()
{
return $this->belongsToMany('App\Station');
}
public function station()
{
return $this->belongsTo('App\Station');
}
}
だから今の問題は、私はにすべての列を記入して、ピボットテーブルにレコードを挿入する方法がわからないということですrole_station
しながら、テーブルstation
やroute
レコードがすでに存在しています。
私が使用しようとしましたattach()
が、それはエラーの下に与えています
照らしなさい/データベース/ QueryExceptionメッセージで'SQLSTATE [HY000]:一般的なエラー:1364フィールド'station_order'はデフォルト値はありません(SQL:への挿入
route_station
(route_id
、station_id
)の値(2、4))'
私はこれで助けを必要とするので、
質問:
私は設定して私を求めているエラー理解
station_order
列の値を私は>私は値を渡すことができますかわかりませんnext_station_id
、interchange_station_id
、station_order
、distance
、duration
デフォルトでは、唯一のモデルキーが上に存在するpivot
オブジェクト。あなたのピボットテーブルは、余分な属性が含まれている場合の関係を定義するとき、あなたはそれらを指定する必要があります。
return $this->belongsToMany('App\Route')->withPivot('next_station_id', 'interchange_station_id', 'station_order', 'distance', 'duration');