2017-10-11 115 views
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(); 

回答

1

而不是手動設置bear_id的魚模型,Eloquent爲您提供了一種方式來模擬associate。請注意,我正在使用靜態create()方法,而不是實例化新模型並分別填入屬性。

$fish = fish::create(['type_of_fish' => json_encode($fishType)]); 
$bear = bear::create(['Name' => $request->input('name_of_bear'); 

$fish->bears()->associate($bear); 
$fish->save(); 

但是,因爲你沒有在這一點上與現有的資源處理,你可以用雄辯對關係create方法。

$bear = Bear::create(['Name' => $request->input('name_of_bear')]); 
$bear->fishes()->create(['type_of_fish' => $fishType); 

這將創建一條新魚,然後自動將它與上面創建的熊關聯起來。

+0

是否有可能在獨立的控制器中分離創建功能,並做一個關聯?因爲我正在創建一個帶有2個頁面的表單,這個頁面會接受用戶輸入,而且我不知道在控制器內部應該做什麼 – blastme

相關問題