将外键值存储在laravel中

问题描述 投票:2回答:1

在迁移表中:

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" => 25当我使用dd($passw1); regist_id只是没有在DB表中获得商店。

我在哪里做错?

laravel eloquent migration database-migration mass-assignment
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.