【发布时间】:2017-10-11 01:41:19
【问题描述】:
我需要一些帮助,使用一对多关系将数据保存到我的数据库中(一条鱼多鱼)。如果你能告诉我一些关于如何做到这一点的例子,那就太好了。因为我的bear_id 为0,所以我似乎无法获取数据。(例如:bear_id = 1 可以检索1 和2 的fish_id)
这是我的代码:
对于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();
【问题讨论】: