【问题标题】:Why is Eloquent not seeing all fields in my model when inserting into the database为什么在插入数据库时​​ Eloquent 看不到我模型中的所有字段
【发布时间】:2019-03-11 10:41:39
【问题描述】:

我是 Laravel 开发的新手,我正在尝试创建一个由 SQLite 数据库支持的 Eloquent 模型。我的本地开发服务器上有以下代码,它正确地接受请求,构建模型,并将该模型保存为 callback_requests 表中的一行。

下面是模型定义文件和数据库迁移文件。我已经使用

运行了迁移
php artisan migrate:reset --force
php artisan migrate 

CallbackRequest.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CallbackRequest extends Model
{
    public $name;
    public $phone;
    public $email;
    public $preferredTime;
}

create_callback_requests_table(迁移).php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCallbackRequestsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('callback_requests', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
            $table->string('phone');
            $table->string('email');
            $table->string('preferredTime');
            $table->string('name');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('callback_requests');
    }
}

这是我创建模型的新实例的控制器文件,使用来自传入请求的值填充它,并将其保存到数据库。

MailController.php

namespace App\Http\Controllers;

use App\Models\CallbackRequest;
use App\Mail\CallbackRequestMailable;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Mail\Mailable;
use Illuminate\Support\Facades\Mail;

class MailController extends Controller
{
    public function send(Request $request) 
    {
        $cbReq = new CallbackRequest();
        $cbReq->name = $request->get('name');
        $cbReq->email = $request->get('email');
        $cbReq->phone = $request->get('phone');
        $cbReq->preferredTime = $request->get('preferredTime');
        var_dump($cbReq);
        // save the entity to the database in case mail gets lost in transit
        $cbReq->save();
        // send an email to the address configured in the .env file
        $result = Mail::to(env("MAIL_CALLBACK_DELIVERY_ADDRESS"))->send(new CallbackRequestMailable($cbReq));
    }
}

我已经转储了 $cbReq 变量的内容以确保正确添加了值,并且我得到的输出(如下所示)表明它们有

object(App\Models\CallbackRequest)#222 (30) {
  ["name"]=>
  string(13) "Customer Name"
  ["phone"]=>
  string(9) "012345678"
  ["email"]=>
  string(14) "cust@email.com"
  ["preferredTime"]=>
  string(7) "morning"
  ["connection":protected]=>
  NULL
  ["table":protected]=>
  NULL
  ["primaryKey":protected]=>
  string(2) "id"
  ["keyType":protected]=>
  string(3) "int"
  ["incrementing"]=>
  bool(true)
  ["with":protected]=>
  array(0) {
  }
  ["withCount":protected]=>
  array(0) {
  }
  ["perPage":protected]=>
  int(15)
  ["exists"]=>
  bool(false)
  ["wasRecentlyCreated"]=>
  bool(false)
  ["attributes":protected]=>
  array(0) {
  }
  ["original":protected]=>
  array(0) {
  }
  ["changes":protected]=>
  array(0) {
  }
  ["casts":protected]=>
  array(0) {
  }
  ["dates":protected]=>
  array(0) {
  }
  ["dateFormat":protected]=>
  NULL
  ["appends":protected]=>
  array(0) {
  }
  ["dispatchesEvents":protected]=>
  array(0) {
  }
  ["observables":protected]=>
  array(0) {
  }
  ["relations":protected]=>
  array(0) {
  }
  ["touches":protected]=>
  array(0) {
  }
  ["timestamps"]=>
  bool(true)
  ["hidden":protected]=>
  array(0) {
  }
  ["visible":protected]=>
  array(0) {
  }
  ["fillable":protected]=>
  array(0) {
  }
  ["guarded":protected]=>
  array(1) {
    [0]=>
    string(1) "*"
  }
}

但是,当应用程序在保存时遇到错误时,会显示以下消息。

{
    "message": "SQLSTATE[HY000]: General error: 1364 Field 'phone' doesn't have a default value (SQL: insert into     `callback_requests` (`updated_at`, `created_at`) values (2019-03-11 10:19:24, 2019-03-11 10:19:24))",
    "exception": "Illuminate\\Database\\QueryException",
    ...
}

从错误消息来看,好像 Eloquent 不知道自定义列,并且试图仅填充自动增量 ID 和时间戳。奇怪的是,当我在本地服务器上运行相同的代码时,一切正常,只有将代码部署到测试服务器时才会遇到错误。

对这个冗长的问题表示歉意,我试图尽可能少地包含,同时不遗漏任何相关内容。任何建议将不胜感激。

【问题讨论】:

    标签: php laravel activerecord eloquent


    【解决方案1】:

    您需要从模型中删除您的属性。所以删除所有这些:

    public $name;
    public $phone;
    public $email;
    public $preferredTime;
    

    否则,当您设置 $model->phone = $request->phone 时,它会在您的对象上设置此属性,而不是在模型的 $attributes 数组中设置键,这是保存到数据库的内容。

    这是由于 Laravel 挂钩了 PHP 魔术方法 __set() 来设置模型的属性。这是基础模型类中的内容:

    /**
     * Dynamically set attributes on the model.
     *
     * @param  string  $key
     * @param  mixed  $value
     * @return void
     */
    public function __set($key, $value)
    {
        $this->setAttribute($key, $value);
    }
    

    如果您的 IDE 的 IntelliSense(自动完成)具有这些属性,您仍然可以使用 docblock 来提示动态属性:

    /**
     * Class CallbackRequest
     *
     * @property-read string name
     * @property-read string phone
     * @property-read string email
     * @property-read string preferredTime
     */
    class CallbackRequest extends Model {}
    

    或使用Laravel IDE helper 之类的包来自动执行此步骤。

    【讨论】:

    • 感谢您的快速响应,特别是您解释问题的根本原因!这很有魅力。
    猜你喜欢
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 2013-06-22
    • 2011-07-30
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多