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