【问题标题】:Laravel 4.2.8 > many to many > create a new related model and attach > errorLaravel 4.2.8 > 多对多 > 创建新的相关模型并附加 > 错误
【发布时间】:2014-10-13 06:26:05
【问题描述】:

不明白为什么在插入新邮政编码并将其与使用 laravel eloquent belongsToMany 功能的现有公司关联时会出现此错误。

这是我的设置:

错误

file: "...\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php"
line: 411
message: "postcode"
type: "Illuminate\Database\Eloquent\MassAssignmentException"


插入代码

$postcode = new Postcode(array('postcode' => $data['plz']));
Company::find($data['id'])->postcodes()->save($postcode);


公司模式

class Company extends Eloquent {

    public function postcodes()
    {
        return $this->belongsToMany('Postcode');
    }
}


邮政编码模型

class Postcode extends Eloquent {

    public function companies()
    {
        return $this->belongsToMany('Company');
    }

}


邮政编码

| id | postcode |


company_postcode

| id | postcode_id | company_id |


公司

| id | name |


有人知道为什么这不起作用吗?

【问题讨论】:

    标签: laravel many-to-many relationship


    【解决方案1】:

    错误提示

    MassAssignmentException

    那是因为你试图批量分配postcode

    new Postcode(array('postcode' => $data['plz']));
    

    因此,请确保将邮政编码变量列入可批量分配的白名单

    class Company extends Eloquent {
    
        protected $fillable = array('postcode');
    
        public function postcodes()
        {
            return $this->belongsToMany('Postcode');
        }
    }
    

    【讨论】:

    • 我认为这有帮助......但我不得不在 Postcode-Model 中声明 $fillable 而不是在公司一中......仍在测试
    • 是的,抱歉,我的意思是让它成为邮政编码模型 - 我复制了你代码的错误部分 :)
    猜你喜欢
    • 2017-03-02
    • 2018-12-16
    • 2014-10-29
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 2017-07-10
    • 1970-01-01
    • 2018-07-10
    相关资源
    最近更新 更多