Laravel - inserting foreign keys causes Integrity constraint violation

匿名 (未验证) 提交于 2019-12-03 01:09:02

问题:

I have two related models Domainand Server. I'm trying to insert data to my tables using a form. here is my store function :

public function store(Request $request, Domain $domain, Server $server) {     $domain->create($request->all());      $server->domain()->associate($domain);     $server->save();     $server->create($request->only(['srv_hostname','srv_ip','srv_port']));      return redirect()->route('domains.index'); }

the table servers has a FK domain_id that points to the PK domain.id Once I submit my form i get the error :

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'domain_id' cannot be null (SQL: insert into servers (domain_id, updated_at, created_at) values (, 2015-11-25 10:55:45, 2015-11-25 10:55:45))

It seems like fk is not correctly linked to the pk..but I don't know how to solve this. thanks :)

Notes :

1 - My 2 related models:

Class Server extends Eloquent {     public function domain(){     return $this->belongsTo('Domain');    } // $fillable and stuff.. }

-

Class Domain extends Eloquent {     public function servers(){     return $this->hasMany('Server'); } // }

2 - My tables are related:

Schema::table('servers', function($table){     $table->foreign('domain_id')         ->references('id')         ->on('domains')         ->onDelete('cascade'); });

回答1:

Have you tried?

  $new_domain = $domain->create($request->all());    $server->domain()->associate($new_domain);   $server->save();


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!