如何在OctoberCMS的数据透视表中为附加列设置值? [英] How to set value for additional column in pivot table in OctoberCMS?

查看:106
本文介绍了如何在OctoberCMS的数据透视表中为附加列设置值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有doctorspecialization表,并且有doctor_specialization_pivot表.在我的数据透视表中,我具有以下列:

I have doctor and specialization table, and have doctor_specialization_pivot table. In my pivot table I have the following columns:

| doctor_id | additional_data | specialization_id |

| doctor_id | additional_data | specialization_id |

additional_datadoctor_id来自doctor模型.

在我的doctor模型文件中,我有以下关系:

In my doctor model file, I have this relationship:

public $belongsToMany = [
    'specialization' => [
        'path\to\specialization\model', 
        'table' => 'doctor_specialization_pivot', 
        'parentKey' => 'doctor_id', 
        'otherKey' => 'specialization_id',
    ]
];

现在在提交表单期间,出现此错误:

Now during submit of form, I'm getting this error:

SQLSTATE[HY000]: General error: 1364 Field 'additional_data' doesn't have a default value (SQL: insert into doctor_specialization_pivot (doctor_id, specializations_id) values (1, 3))"

我尝试添加到我的关系'pivot' => ['additional_data'].但是仍然出现相同的错误.

I tried adding to my relationship 'pivot' => ['additional_data']. But still getting the same error.

我检查了提交的数据,并且additional_data不为空.我从OctoberCMS论坛进行了检查,但没有得到直接的答案,例如

I checked the submitted data and additional_data is not empty. I checked from OctoberCMS forums but not getting straight forward answers such as this and this.

推荐答案

好的.我找到了自己问题的答案.

Okay. I found the answer to my own question.

我将详细回答以帮助所有人.经过挖掘和盲目射击.根据此文档此处,我们可以使用方法attach() 通过在连接模型的中间表中插入一条记录来将角色附加到用户上.

I'll answer in detail to help everyone. After digging and blind shooting. According to this documentation here, we can use the method attach() to attach a role to a user by inserting a record in the intermediate table that joins the models.

文档中让我感到困惑的是,它使用了$roleId变量,而我不明白$roleId的来源.如果是父表的id或其他表的id.

What confuse me in the documentation is that it uses a $roleId variable and I didn't understand where the $roleId came from. If it's the id of the parent table or the id of other table.

链接示例:

$user = User::find(1);

$user->roles()->attach($roleId);

所以我在doctor模型中所做的事情,我挂接到事件beforeSave,使用关系($this->specialization)作为第一个参数,而不是文档中的id. $this->specialization()也是在belongsToMany中定义的关系.

So what I did in my doctor model, I hook to the event beforeSave, use the relationship ($this->specialization) as the first parameter instead of the id in the docs. The $this->specialization() is the relationship too defined in belongsToMany.

答案:

public function beforeSave()
{
    $this->specialization()->attach($this->specialization,['additional_data' => 'additional data from doctor table']);
}

这篇关于如何在OctoberCMS的数据透视表中为附加列设置值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆