【问题标题】:Laravel create method returning nullLaravel 创建方法返回 null
【发布时间】:2016-02-20 07:31:11
【问题描述】:

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

组模型

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

【问题讨论】:

    标签: php mysql laravel-5.2


    【解决方案1】:

    在组模型中

    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

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

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

    【讨论】:

    • 我已经有protected $fillable = ['group_name'];,就在模型的开头。插入有效,但问题是它没有返回lastInsertId,尽管在数据库中创建了记录。如果我提供的信息很少,我很抱歉
    • 我已经更新了答案。请让我知道它是否有效。
    • 感谢您的建议,我尽量不使用查询生成器。在这种情况下,我宁愿只调用 save 方法。如果create 只返回true,那么为什么这个工作laracasts.com/series/laravel-5-fundamentals/episodes/23 - 跳到1:00,他正在使用create 方法。
    • 为什么你的方法中有protected $fillable
    【解决方案2】:

    我想通了。我改变了这个:

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

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

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

    【讨论】:

    • 这很有用,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2021-03-08
    • 1970-01-01
    • 2020-09-07
    • 2013-11-19
    相关资源
    最近更新 更多