Laravel create方法返回null

时间:2016-02-20 07:31:11

标签: php mysql laravel-5.2

我有这个问题。我有一个组和角色模型,具有多对多关系设置。

群组模型

public function roles()
{
    return $this->belongsToMany('App\Role', 'group_roles');
}

角色模型

public function groups()
{
    return $this->belongsToMany('App\Group', 'group_roles');
}

GroupsController商店方法

public function store(Request $requests)
{
    $group = new Group;
    //$group->group_name = $requests->group_name;
    //$group->save();
    $group->create($requests->all());

    $group->roles()->sync($requests->input('roles'));


   Session::flash('success', $requests->group_name.' successfully added');
   return redirect('/settings/groups/groups');

}

我在这里遇到的问题是,当我在组模型上调用create方法时,它返回null,从而导致此$group->roles()->sync($requests->input('roles'));失败。但是,当我使用save方法时,它可以完美地工作。为什么创作不起作用?

编辑:如果我使用create,它会将记录插入数据库,但问题是它不会返回insertLastId

2 个答案:

答案 0 :(得分:0)

在组模型中

public function groups()
{
    protected $fillable = ['group_name'] //add all the fillable fields
    return $this->belongsToMany('App\Group', 'group_roles');
}  

使用create()方法时,它会批量指定所有值,因此应在该特定模型中使用protected $fillable = []。见https://laravel.com/docs/5.1/eloquent#mass-assignment

For Last Insert Id使用db函数,因为create()方法不返回lastInsertId,如果数据插入成功,它只返回true

return DB::('table_name')->insertGetId([
    'group_name' => 'some name'
]);

答案 1 :(得分:0)

我已经弄清楚了。我改变了这个:

$group = new Group;
$group->create($requests->all());

$group = Group::create($requests->all())

现在create返回最后一个插入ID。