为什么 Eloquent 在插入数据库时​​看不到模型中的所有字段

Jac*_*ill 2 php activerecord laravel eloquent

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

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

php artisan migrate:reset --force
php artisan migrate 
Run Code Online (Sandbox Code Playgroud)

回调请求.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CallbackRequest extends Model
{
    public $name;
    public $phone;
    public $email;
    public $preferredTime;
}
Run Code Online (Sandbox Code Playgroud)

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

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

邮件控制器.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));
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经转储了 $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) "*"
  }
}
Run Code Online (Sandbox Code Playgroud)

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

{
    "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",
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

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

Tra*_*itz 5

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

public $name;
public $phone;
public $email;
public $preferredTime;
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

/**
 * Class CallbackRequest
 *
 * @property-read string name
 * @property-read string phone
 * @property-read string email
 * @property-read string preferredTime
 */
class CallbackRequest extends Model {}
Run Code Online (Sandbox Code Playgroud)

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