用户表
id (primary key), name, email
用户模型
protected $fillable = ['name', 'email'];
protected $visible = ['id','name','email'];
//Relationship
public function customAttributes()
{
return $this->hasMany('App\Models\UserAttribute');
}
user_id, attribute_id, value //user_id and attribute_id is a composite key, both foreignkeys acting as primary keys establishing an unique combination
用户属性模型
protected $fillable = ['user_id', 'attribute_id','value'];
protected $visible = ['user_id', 'attribute_id','value'];
我将使用以下示例来解释这个问题:
$user = $this->user->create(['name' => 'admin', 'email' => 'admin@admin.com']);
//This works
$user->customAttributes()->save(new \App\Models\UserAttribute(['user_id' => $user->id, 'attribute_id' => 1, 'value' => 'Just a custom1']));
//This does not work
$user->customAttributes()->create([new \App\Models\UserAttribute(['user_id' => $user->id, 'attribute_id' => 1, 'value' => 'Just a custom1'])]);
save
我想要的每一个习惯,因为它的工作,但我试图找出原因
create
不起作用。
我使用create时遇到的错误是(是的,我已经检查了表中存在的记录,但这里没有列出):
Cannot add or update a child row: a foreign key constraint fails (`testdatabase`.`user_attributes`,
CONSTRAINT `user_attributes_attribute_id_foreign` FOREIGN KEY (`attribute_id`) REFERENCES `attributes` (`id`))
这是它试图执行的查询:
insert into `user_attributes` (`user_id`) values (1)
我只是好奇为什么这不适用于
创造
,我不确定它是否与此特定场景相关(按关系创建复合键表)。有点忽略了
value
attribute_id
正在执行的查询中的字段