【问题标题】:Laravel - Array to string conversion error on Model::create or Model->save()Laravel - Model::create 或 Model->save() 上的数组到字符串转换错误
【发布时间】:2014-12-17 11:48:53
【问题描述】:

我正在执行一个简单的插入,我已经做了很多次没有任何问题,但由于某些奇怪的原因它不起作用,我收到以下错误消息:

error: {type: "ErrorException", message: "Array to string conversion",…}
file: "C:\wamp\www\studentreg2\vendor\laravel\framework\src\Illuminate\Database\Grammar.php"
  line: 33
  message: "Array to string conversion"
  type: "ErrorException"

这是我的代码:

$advisorCheck = AdvisorCheck::create([
            'status'         => Input::get('status'),
            'application_id' => Input::get('id'),
            'user_id'        => Auth::id()
        ]);

AdvisorCheck 模型使用的 advisor_check 表的迁移似乎很好,所有外键都未签名并在 phpmyadmin 中正确显示关系,来自 Input::get 的所有值都是字符串,模型将正确的字段设置为可填充(状态、应用程序 ID、用户 ID)。

我什至尝试在php artisan tinker 中这样做:

AdvisorCheck::create([ 'status' => 'returned', 'application_id' => '3', 'user_id' => '4']);

我得到了这样的回应: 数组到字符串的转换

我也试过这个方法,得到同样的错误:

$advisorCheck                 = new AdvisorCheck;
$advisorCheck->status         = Input::get('status');
$advisorCheck->application_id = Input::get('id');
$advisorCheck->user_id        = Auth::id();
$advisorCheck->save();

型号代码:

<?php

class AdvisorCheck extends \Eloquent {

    protected $fillable = ['status', 'application_id', 'user_id'];

    protected $table = ['advisor_check'];
}

如果您需要查看更多代码,请询问。

非常感谢任何可以提供帮助的人!

【问题讨论】:

  • 模型中有什么不寻常的地方吗?
  • 我有一种感觉,因为我把 $table 放在 $fillable 之前,我所有的其他模型都先有 $fillable - 现在试一试
  • 不,不是吗 - 我猜这没有任何意义?我将发布模型代码
  • table 属性必须是字符串而不是数组!
  • @lukasgeiter 好地方。

标签: php laravel eloquent


【解决方案1】:

正如您在Laravel docs 中显示的示例中看到的,表格属性是一个字符串,而不是一个数组

protected $table = 'advisor_check';

如果您考虑一下,这完全有道理,因为 Eloquent 模型本身不支持多个表。

【讨论】:

    【解决方案2】:

    $table 应该是字符串而不是数组

    <?php
    
       class AdvisorCheck extends \Eloquent {
    
       protected $fillable = ['status', 'application_id', 'user_id'];
    
       protected $table = 'advisor_check';
    }
    

    【讨论】:

      【解决方案3】:

      如果我们在 laravel 模型中像数组一样给出表名:

       protected $table = ['thoughts'];
      

      那么它会产生错误。

      所以你应该将表名作为字符串给出:

      protected $table = 'thoughts';
      

      【讨论】:

        猜你喜欢
        • 2020-01-30
        • 2019-12-31
        • 1970-01-01
        • 2015-06-27
        • 2019-05-01
        • 2022-01-25
        • 2018-04-05
        • 2016-09-01
        • 1970-01-01
        相关资源
        最近更新 更多