簡體   English   中英

使用laravel將一對多關系保存到數據庫中

[英]Saving a one to many relationship into a database using laravel

我需要一些幫助,使用一對多關系(將一條魚養一條魚)將數據保存到數據庫中。 如果您可以向我展示一些有關如何執行此操作的示例,那將很好。 因為我的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();

Eloquent無需手動設置魚類模型的bear_id,而是為您提供了一種關聯模型的方法。 請注意,我使用的是靜態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();

但是,由於此時您不處理現有資源,因此可以將Eloquent的create方法用於關系。

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

這將創建一條新的魚,然后將其與上一行中創建的熊自動關聯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM