我有两张桌子routes
and stations
和一个数据透视表route_station
。详见表格
路线表
id, number, code
车站表
id, name, code
路线站表(枢轴)
id, route_id, station_id, next_station_id, interchange_station_id, sation_order, distance, duration
station_id
, next_station_id
, interchange_station_id
全部都是satations
表号
Schema
Station
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();
}
);
Route
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');
}
);
在管理区域中,共有三个部分来管理车站和路线。
- 车站页面
- 路线页面
- 我可以在其中添加车站到路线的页面
这意味着我不会在创建数据透视表时将记录插入到数据透视表中station
or route
但从上面提到的第 3 页以后的任何时间。
我现在有两个型号Station
and 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
and route
记录已经存在。
我尝试过使用attach()
但它给出以下错误
使用消息 'SQLSTATE[HY000] 照亮/数据库/QueryException:
一般错误:1364 字段“station_order”没有默认值
(SQL:插入route_station
(route_id
, station_id
) 值
(2, 4))'
所以我需要这方面的帮助
问题:
我理解要求我设置的错误station_order
列值,但我不知道如何传递值next_station_id
, interchange_station_id
, station_order
, distance
, duration