2017-08-29 109 views
0

我试图用一种方法插入到2个不同的表格(House和Contact)中。如何使用Laravel插入多个表格

public function store(HouseRequest $request){ 

    $dataForm = $request->all(); 

    $house = House::create($dataForm); //Insert into House table 
    $contact = $house->contact()->create($dataForm['contact']); //Insert into Contact table 


    return back('dashboard/houses')->with('message', 'Success'); 
} 

这里是我的表联系人:

Schema::create('contacts', function (Blueprint $table) {  
     $table->integer('house_id')->unsigned(); 
     $table->string('name', 255); 
     $table->char('phone', 11); 
     $table->timestamps(); 

     $table->foreign('house_id')->references('id')->on('houses')->onDelete('cascade') 
    } 

楼型号:

public function contact(){ 
    return $this->hasOne(Contact::class); 
} 

它工作正常(插入到两个表),但提交表单后,我得到这个:

SQLSTATE [42S22]:未找到列:1054'where子句'中的未知列'id'(SQL:select * from contacts其中id = 0限制1)

我不知道它为什么运行上面的查询。我怎样才能摆脱这个错误?

回答

2

你忘记添加一个列中的ID添加迁移$table->increments('id');

Schema::create('contacts', function (Blueprint $table) { 
    $table->increments('id'); 
    $table->integer('house_id')->unsigned(); 
    $table->string('name', 255); 
    $table->char('phone', 11); 
    $table->timestamps(); 

    $table->foreign('house_id')->references('id')->on('houses')->onDelete('cascade') 
} 
+1

它是如此简单,我真的需要得到一些睡眠; – GabrielFiel