【问题标题】:Saving a one to many relationship into a database using laravel使用 laravel 将一对多关系保存到数据库中
【发布时间】: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();

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案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);
    

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

    【讨论】:

    • 是否可以在单独的控制器中分离创建功能并进行关联?因为我正在创建一个包含 2 个页面的表单,它接受用户输入,但我不知道在控制器内部做什么
    猜你喜欢
    • 2014-05-20
    • 2014-05-31
    • 2018-03-20
    • 2015-03-05
    • 2018-07-16
    • 1970-01-01
    • 2019-11-12
    • 2021-08-29
    • 1970-01-01
    相关资源
    最近更新 更多