使用laravel将一对多关系保存到数据库中

时间:2017-10-11 01:41:19

标签: php laravel laravel-5

我需要一些帮助,使用一对多的关系将数据保存到我的数据库中(一个承载很多鱼)。如果你能告诉我一些如何做的例子,那将会很棒。因为我似乎无法获取数据,因为我的bear_id为0.(例如:bear_id = 1可以检索1和2的fish_id)

以下是我的代码:

for 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 个答案:

答案 0 :(得分:1)

Eloquent不是手动设置鱼模型的bear_id,而是为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();

但是,由于此时您尚未处理现有资源,因此可以使用Eloquent的create方法进行关系。

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

这将创建一条新鱼,然后自动将其与上面一行中创建的熊联系起来。