0
我需要一些帮助,使用一对多关系(一个承载许多鱼)将数据保存到我的数据库中。如果你能告诉我一些关于如何去做的例子,那将是非常棒的。因为我似乎无法获得数据,因为我bear_id为0(如:bear_id = 1可以检索的1 fish_id和2)使用laravel将一对多关系保存到数据库中
这里是我的代码:
为blade.php:
{{Form::text('name_of_bear, '', ['class' => 'form-control'])}} --> first page, once user has entered bear name it will redirect it to the fish page to enter the checkbox
<input type="checkbox" id="inlineCheckbox1" name="type_of_fish[]" value="Salmon"> Salmon <input type="checkbox" id="inlineCheckbox1" name="type_of_fish[]" value="Sardine"> Sardine --> second page after user has entered the data for bear they will click next and be redirected to here
为我的表:
Schema::create('bears, function (Blueprint $table) {
$table->increments('id');
$table->engine = 'InnoDB';
$table->string(name);
$table->timestamps();
});
Schema::create(fishs, function (Blueprint $table) {
$table->increments('id');
$table->engine = 'InnoDB';
$table->string(name);
$table->integer(bear_id);
$table->timestamps();
});
鱼模型:
class fish extends Eloquent
{
protected $fillable = array('name', 'bear_id');
// DEFINE RELATIONSHIPS
public function bears() {
return $this->belongsTo('App\bear);
}
}
熊市型号:
class bear extends Eloquent
{
protected $primaryKey = 'id';
public function fishs() {
return $this->hasMany('App\fish,'bear_id');
}
}
对于控制器的一部分,我还在学习,所以我真的不知道如何使用它
控制器:
public function view(Request $request)
{
$fish= new fish();
$fishType= $request->input('type_of_fish');
$fish->type_of_fish= json_encode($fishType);
$fish->save();
$bear= new bear();
$bear->Name = $request->input('name_of_bear');
$bear->save();
$fish->bear_id = $bear->id;
$fish->save();
是否有可能在独立的控制器中分离创建功能,并做一个关联?因为我正在创建一个带有2个页面的表单,这个页面会接受用户输入,而且我不知道在控制器内部应该做什么 – blastme