即使已设置了可填写数据,也不会将数据保存到数据库中

时间:2017-10-13 02:19:15

标签: php laravel one-to-many

在我的数据库中我试图将我的数据保存到数据库,表鱼,但只保存了我的bear_id而不是fish_location或fish_type。有人可以帮忙吗?

信息:一只熊有很多鱼(一对多的关系)

位指示:

 public function submit(Request $request)
{

$bear= Session::get('data');


$test = array();
$test['fish_location'] = $request->fish_location;
$test['fish_type'] = $request->fish_type;
$fish = new fish;
$fish = fish::create([$test]);
$fish->bears()->associate($bear);
$fish->save();
return ('thank you');

}

鱼模型:

class fish extends Eloquent
{
        protected $fillable = array('fish_type', 'fish_location', 'bear_id');


    public function bears() {
        return $this->belongsTo('App\bear');
    }

鱼桌:

Schema::create('fishs', function (Blueprint $table) {
    $table->increments('id');
    $table->engine = 'InnoDB';  
    $table->string('fish_location');
    $table->string('fish_type'); 
    $table->integer('bear_id');
    $table->timestamps();
});

2 个答案:

答案 0 :(得分:1)

create()方法需要设置一组数据。你实际传入的是一个包含数据数组的数组。删除周围的[]你应该是好的:

$fish = fish::create($test);

答案 1 :(得分:0)

调用$ fish-> save();在$ fish-> bears() - > associate($ bear)之前;

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
   imports: [NgbModule, ...],
})

或尝试

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