Table 专业 Laravel

Table Specialization with Laravel

使用 mySql,我创建了 3 个 table:vehiclescarsbikes。 表 carsbikes 是 table vehicles(子 table)的特化。

vehicles 有一个名为 id 的主键。

carsbikes 没有主键。相反,他们还有一个名为 id 的字段,上面有一个索引,其中包含与 vehicles.id 相同的值以充当外键。

使用 Laravel 5.3 框架,我尝试首先将一条新记录插入 vehicles,然后将一条新记录插入 cars,如下所示:

$id = Vehicle::create(['name'=>'volvo'])->id;
Car::create(['id'=>$id, 'nbDoors'=>4]);

我收到以下错误:

QueryException in Connection.php line 770: SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value (SQL: insert into cars (nbDorrs) values (3))

是否有解决方案或更好的数据库设计,以便我可以在两个 table 中插入数据并保持这种专业化?

找到解决方法: 我只是省略了将 id 添加到 Car 模型中的可填充列!

class Car extends Model
{
  /**
   * The attributes that are mass assignable.
   *
   * @var array
   */
  protected $fillable = ['id', 'nbDoors'];