gpt4 book ai didi

php - Laravel 的表特化

转载 作者:行者123 更新时间:2023-11-29 19:36:59 27 4
gpt4 key购买 nike

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

vehicles 有一个名为 id 的主键。

汽车自行车没有主键。相反,它们还有一个名为 id 的字段,其上有一个索引,其中包含与 vehicles.id 相同的值来充当外键。

enter image description here

使用 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))

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

最佳答案

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

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

关于php - Laravel 的表特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41525891/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com