2017-06-20 148 views
0

我正在使用firsOrCreate方法来保存记录,如果它们已经不存在于数据库中。这是我的函数:Laravel - firstOrCreate没有坚持所有字段到数据库

return ContentType::firstOrCreate(
    ['name' => $type], ['slug' => str_slug($type, '-')] 
); 

我这里的问题是,新的记录在数据库中创建,但塞领域保持为空。不知道这是为什么,因为塞被创建,因为当我做

dd(str_slug($type, '-')); 

方法firstOrCreate()之前,我得到了塞。 那么,为什么它没有坚持到数据库?

我已经在我的模型建立保护森严阵列所以,这不应该成为问题:

protected $guarded = [ 
     'id' 
    ]; 
+0

应该不是所有的领域是在单个阵列中,即'[” name'=> $ type,'slug'=> str_slug($ type,' - ')]'? – apokryfos

回答

0

您需要确保蛞蝓和name属性是可填写。

如果ContentType模型,确保可填充的属性看起来像:

class ContentType 
{ 
    protected $fillable = ['name', 'slug']; 
} 
+0

但是,这就是https://laravel.com/docs/5.4/eloquent文档中的那种方式,您需要为要搜索表的列以及要保留的字段数组使用单独的数组模型在DB中不存在 – Leff

+0

你是对的,我已经更新了我的答案 - 我没有正确地阅读这个问题。 – LMS94

+1

其实,你的第一个答案是正确的,我正在使用遗留代码,并没有检查版本,因为事实证明,我有v5.2,firstOrCreate只需要一个数组。 – Leff

0

是您slug场在$fillable属性模型中的阵列?否则它不会被插入,由于它被保护:

use Illuminate\Database\Eloquent\Model; 

class ContentType extends Model 
{ 
    /** 
    * The attributes that are mass assignable. 
    * 
    * @var array 
    */ 
    protected $fillable = [ 
     'name', 
     'slug', 
    ]; 
} 

对于别人看,Laravel 5.3/5.4支持本次阵列:

https://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Eloquent/Builder.php#L349-L365

https://github.com/laravel/framework/blob/5.3/src/Illuminate/Database/Eloquent/Builder.php#L251-L271

然而Laravel 5.2及以下版本不:

https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Builder.php#L243-L260

在模型中
0

第一设置$可填写如下:

/** 
    * The attributes that are mass assignable. 
    * 
    * @var array 
    */ 
    protected $fillable = [ 
     'name', 
     'slug', 
    ]; 

请尝试以下方法插入

$data = array(
    'name' => $type, 
    'slug' => str_slug($type, '-') 
    ); 

return ContentType::firstOrCreate($data);