【发布时间】:2020-10-13 03:23:26
【问题描述】:
我有两个关系表,其中包含枢轴 routes、stations 和 route_station。 routes 表包含地铁的路线编号,stations 包含所有车站。
数据透视表多条路线和每条路线的多个站点。所以不知道如何考虑。 many-to-many 还是 one-to-many?
HTML 表单
Route 上的 HTML 表单包含需要插入数据透视表的可克隆字段。见下文。
- 车站
- 下一站
- 距离
- 持续时间
问题
所以我的问题是如何插入可克隆字段数据(在上面 list) 以便在 pivot 表中为每个克隆字段插入行?
还有我如何更新,以便更新数据透视表中的确切记录 表,如果克隆字段被删除,那么数据透视表中的记录 表也删除了?
路由架构
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');
}
);
站架构
Schema::create(
'stations',
function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->index()->unique();
$table->string('code')->index()->unique();
$table->text('info');
$table->string('photo')->nullable();
$table->timestamps();
}
);
路由站(枢轴)架构
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();
$table->integer('station_order');
$table->float('distance');
$table->integer('duration');
$table->timestamps();
$table->unique(['route_id', 'station_id'], 'route_station_unique');
$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');
}
);
路线创建/更新表格
更新
我在下面尝试过但没有工作。给出Array to String conversion 错误。这是因为,我相信attach 和sync 只插入一条记录,而请求字段是一个数组。
那么如何为数组的每一项插入一条记录呢?
$route = Route::create([
'number' => $request->number,
'code' => strtoupper($request->code),
]);
$route->stations()->sync($route, [
'next_station_id' => $request->next_station_id,
'distance' => $request->distance,
'duration' => $request->duration,
'station_order' => $request->station_order,
]);
【问题讨论】:
-
这里有一些可以帮助你的,只要选择正确的laravel版本laravel.com/docs/7.x/eloquent-relationships
标签: laravel eloquent many-to-many relationship one-to-many