代码之家  ›  专栏  ›  技术社区  ›  abr

按关系插入复合键表

  •  0
  • abr  · 技术社区  · 6 年前

    用户表

    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 正在执行的查询中的字段

    2 回复  |  直到 6 年前
        1
  •  1
  •   Jinal Somaiya    6 年前

    试试这个:

    $user->customAttributes()->create(['user_id' => $user->id, 'attribute_id' => 1, 'value' => 'Just a custom1']);
    
        2
  •  1
  •   Teoman Tıngır    6 年前

    customAttributes() 已经返回了UserAttribute模型的实例,在使用时不需要约束该依赖关系 create()

    您的查询应该如下所示;

    $user->customAttributes()->insert([
       [
       'user_id' => $user->id,
       'attribute_id' => 1,
       'value' => 'Just a custom1'
       ],
       [
       'user_id' => $user->id,
       'attribute_id' => 2,
       'value' => 'Just a custom2'
       ],
    ]);