【问题标题】:Laravel mass assignment [1452] errorLaravel 质量分配 [1452] 错误
【发布时间】:2014-07-21 02:21:45
【问题描述】:

MySql 在尝试创建模型的新实例时抛出错误。 user_id 字段有效,我尝试手动设置,但也没有用。存在 ID 为 1 的用户。

错误:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`production_paperclip`.`widgets`, CONSTRAINT `widgets_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION) (SQL: insert into `widgets` (`updated_at`, `created_at`) values (2014-07-21 02:14:12, 2014-07-21 02:14:12)) 

查询:

\Widget::create(array(
        'title'             => \Lang::get('widget.news_localizer.install.title'),
        'strictName'        => self::strictName,
        'userSettings'      => null,
        'description'       => \Lang::get('widget.news_localizer.install.description'),
        'bodyTemplateName'  => 'admin.dashboard.widgets.news_localizer.index',
        'user_id'           => \Auth::id(),
        ));

型号:

class Widget extends \Eloquent
{
   use SoftDeletingTrait;

   protected $fillable = array('*');
   /**
    * Get the user which installed the widget
    * @return Illuminate\Database\Eloquent\Relations\BelongsTo
    */
   public function user()
   {
    return $this->belongsTo('User');
   }
}

迁移:

public function up()
{
    Schema::create('widgets', function(Blueprint $table)
    {
        $table->increments('id');
        // Name
        $table->string('title', 256);
        $table->index('title');

        // Strict name
        $table->string('strictName')->unqiue();

        // User settings
        $table->text('userSettings')->nullable();

        // A short description
        $table->string('description')->nullable();

        // Body template name
        $table->string('bodyTemplateName');

        // User
        $table->integer('user_id')->length(10)->unsigned();
        $table->foreign('user_id')
        ->references('id')->on('users')
        ->onDelete('no action');

        $table->timestamps();
        $table->softDeletes();
    });
}

【问题讨论】:

    标签: php mysql laravel laravel-4 eloquent


    【解决方案1】:

    Widget 模型更改

    protected $fillable = array('*');
    

    protected $guarded = array('id', 'created_at', 'updated_at');
    

    protected $fillable = array('title', 'strictName', 'userSettings', 'description', 'bodyTemplateName', 'user_id');
    

    换句话说,您必须明确指定可填写字段(白名单)或受保护字段(黑名单)。 * 仅适用于$guarded,不适用于$fillable,错误消息清楚地表明了这一点。您只填充了时间戳字段:

    insert into `widgets` (`updated_at`, `created_at`) 
    values (2014-07-21 02:14:12, 2014-07-21 02:14:12)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多