我有两个资源,砖和墙。
Brick
模型定义为
class Brick extends Model
{
public function walls()
{
return $this->belongsToMany('App\Wall')->withTimestamps();
}
}
Wall
模型定义为
class Wall extends Model
{
public function bricks()
{
return $this->hasMany('App\Brick');
}
}
这个想法是一堵墙可以有很多砖,一块砖可以属于很多墙。
在 Nova 中,我将Wall
字段设置为
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Text::make('Name'),
HasMany::make('Bricks')
];
}
和Brick
字段设置为
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Text::make('Name'),
BelongsToMany::make('Walls')
];
}
尝试通过砖资源将砖连接到墙上时,出现错误SQLSTATE[HY000]: General error: 1 no such table: main.wall_id (SQL: insert into "brick_wall" ("brick_id", "wall_id", "created_at", "updated_at") values (5, 1, 2018-11-18 22:08:23, 2018-11-18 22:08:23))
,当尝试通过墙资源将砖添加到墙上时,我得到SQLSTATE[HY000]: General error: 1 no such column: bricks.wall_id (SQL: select * from "bricks" where "bricks"."wall_id" = 1 and "bricks"."wall_id" is not null)
我试过切换belongsToMany
和hasMany
关系,但没有帮助。
编辑:这是中间表的方案
Schema::create('brick_wall', function (Blueprint $table) {
$table->increments('id');
$table->integer('brick_id')->unsigned();
$table->integer('wall_id')->unsigned();
$table->foreign('brick_id')->references('id')->on('brick_id');
$table->foreign('wall_id')->references('id')->on('wall_id');
});