Laravel 4.2.8>多对多>创建一个新的相关模型并附加>错误

时间:2014-08-20 01:43:00

标签: laravel many-to-many relationship

在使用laravels eloquent belongsToMany功能插入新的邮政编码并将其与现有公司联系时,不会发生此错误的原因。

这是我的设置:

错误

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


Insertcode

$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 |


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

1 个答案:

答案 0 :(得分:0)

错误说

  

MassAssignmentException

这是因为您正在尝试批量分配postcode

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

因此,请确保将邮政编码变量列入白名单

class Company extends Eloquent {

    protected $fillable = array('postcode');

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