将外键值存储在laravel中

时间:2018-08-06 12:26:25

标签: laravel eloquent migration database-migration mass-assignment

在迁移表中:

Schema::create('passws', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('regist_id')->unsigned()->nullable();
        $table->foreign('regist_id')->references('id')->on('regists');
        $table->string('age');
        $table->timestamps();
    });
}

注册模型-已定义质量分配。

 public function pass(){
    return $this->hasOne('App\Passw');
}

在控制器中

$name = $request->name;
$task = Regist::whereName($name)->get();
    foreach ($task as $tasks){
        $passw1->regist_id = $tasks->id;
    }
 $passw1->age = $request->age;
 $regist = new Regist();
 $regist->pass()->save($passw1);

当我存储数据时,仅存储age,但是将regist_id存储为null(无错误消息或什么都没有)。在这里,我确定当我使用"regist_id" => 1时,控制器会显示"age" => 25dd($passw1);。regist_id仅未在数据库表中存储。

我在哪里出错?

1 个答案:

答案 0 :(得分:2)

尝试

$name = $request->name;

$regist = Regist::whereName($name)->first(); //it will give you a Regist model

$regist->pass()->create([    
     'age' => $request->age
]);

如果Regist有多个$name,请尝试

$regists = Regist::whereName($name)->get(); //it will give you a collection of Regist model

foreach ($regists as $regist){
    $regist->pass()->create([    
          'age' => $request->age
    ]);
}

在此处https://laravel.com/docs/5.6/eloquent-relationships#the-create-method

检查文档