【问题标题】:Laravel: static::create vs DB:insertLaravel:静态::创建与 DB:插入
【发布时间】:2015-03-04 14:57:16
【问题描述】:

如果我在模型中使用以下代码 sn-p,它会插入数据:

$instance = DB::table('users')->insert(compact('email', 'username'));

但如果我这样做:

$instance = static::create(compact('email', 'username'));

它插入null,但插入created_at和updated_at。

【问题讨论】:

  • 你能告诉我们完整的方法吗($email,$username在哪里)
  • 当然,公共静态函数 store($email, $username){ $instance = static::create(compact('email', 'username')); }
  • DB 方式和 Eloquent 方式相同。
  • 如果你想用单个Medel::xxx 命令添加多行,那么你必须使用::insert($data)

标签: php database laravel eloquent


【解决方案1】:

Laravel 的 created_at/updated_atIlluminate\Database\Eloquent\Model 的一部分。原始的 DB::table 查询构建器不是 Eloquent 模型,因此没有那些自动参数。

NULL 数据被插入到 Eloquent 查询中,因为 Eloquent 有一个您需要定义的 $fillable 参数。此参数设置可以批量分配哪些列。当您执行 fillcreate 或以其他方式实例化一个新对象时,Laravel 会删除此数组中不存在的属性。在您的模型中,您希望:

class User extends Eloquent {
  protected $fillable = ['email', 'username'];
}

【讨论】:

  • 对不起,我没有在上面的 sn-ps 中包含它。但我有一个受保护的 $fillable = ['email', 'username'];
  • 如果您使用User::create(['email' => $email, 'username' => $username]) 而不是compact 调用,它会起作用吗?
  • 您在apache2/error.log 中没有收到任何错误,并且您在 laravel 上启用了调试模式
  • 没有,我从 laravel 得到的唯一“错误”:SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'users_email_unique' (SQL: insert into ``users (updated_at, created_at``) values (2015-01-06 21:52:35, 2015-01-06 21:52:35))
  • @Prezioso 如果$email 为空,或者属性被可填充功能过滤掉,您就会明白这一点。执行dd($email),看看它是否符合您的预期。
【解决方案2】:

ceejayoz 的回答很棒,这里解释了如何调用模型。创建模型后,假设这个模型:

class User extends Eloquent {
  protected $fillable = ['email', 'username'];
}

那么你需要直接使用模型来调用并像这样雄辩ORM:

// example is this. True method is TableName->ColumnName = Value;
$user = User::find($id);
$user->username = '';
$user->fullname = '';
$user->save();

保存将根据您的描述更新列。有了这个,您甚至不需要可填充变量。

其他一些值得了解的模型变量是:

protected $primaryKey = 'userid';   #if you have an primarykey that isn't named id
protected $table = 'tablename';     #if table name isn't pulling by the name of the model
protected $timestamps = true;       #bool value, whether u have timestamp columns in table

【讨论】:

    【解决方案3】:

    你说你做到了

    class User extends Eloquent {
      protected $fillable = ['email', 'username'];
    }
    

    但是在您的评论中您告诉我们您的 apache 日志中出现以下错误

    SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' 
    for key 'users_email_unique' (SQL: insert into ``users 
    (updated_at, created_at``) values (2015-01-06 21:52:35, 2015-01-06 21:52:35))
    

    如果你想设置users_email_unique,请确保在你的可填充数组中也包含它。

    class User extends Eloquent {
      protected $fillable = ['email', 'username', 'users_email_unique'];
    }
    

    【讨论】:

    • users_email_uniquein 是 MySQL UNIQUE 键的名称。它不是列名。
    猜你喜欢
    • 2012-01-05
    • 1970-01-01
    • 2016-06-24
    • 2019-03-16
    • 2017-03-20
    • 2014-04-27
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    相关资源
    最近更新 更多