【问题标题】:Laravel 5.4 ignores $fillableLaravel 5.4 忽略 $fillable
【发布时间】:2017-09-08 09:09:52
【问题描述】:

我正在尝试更新具有由 customer_id 链接到客户表的外键约束的 orders 表。

迁移文件(100% 有效):

Schema::create('orders', function (Blueprint $table) {
            $table->integer('order_id')->unsigned()->index();
            $table->integer('customer_id')->unsigned()->index();
            $table->foreign('customer_id')->references('customer_id')->on('customers')->onDelete('cascade');
            $table->string('order_status');
            $table->string('customer_note')->nullable();
            $table->timestamp('order_date');
            $table->timestamps();
            $table->softDeletes();
            $table->primary(['order_id', 'customer_id']);
        }); 

在我的模型中,我使以下列为可填充的,这样 Laravel 就不会忽略它们:

protected $fillable = [
        'order_id', 'customer_id', 'order_status', 'customer_note', 'order_date',
    ];

当我创建/更新订单时,我在更新方法下的 OrderController 中使用以下代码行。我使用 firstOrCreate() 来确保如果订单以某种方式被删除或从未添加过,这不会失败。

$order = Order::firstOrCreate(['order_id' => $request->input('id')]);
        $order->order_id = $request->input('id');
        $order->customer_id = $request->input('customer_id');
        $order->order_status = $request->input('status');
        $order->customer_note = $request->input('customer_note');
        $order->order_date = $request->input('date_created');
        $order->save();

当我尝试更新订单时,我在日志文件中收到以下错误消息:

Next Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`vcc-backoffice`.`orders`, CONSTRAINT `orders_customer_id_foreign` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`customer_id`) ON DELETE CASCADE) (SQL: insert into `orders` (`order_id`, `updated_at`, `created_at`) values (76, 2017-09-08 08:55:37, 2017-09-08 08:55:37)) in /home/vagrant/Projects/vcc-backoffice/vendor/laravel/framework/src/Illuminate/Database/Connection.php:647 

我注意到插入语句只尝试插入 3 列。 order_idupdated_atcreated_at

我假设无法创建该行,因为没有填充外部 *customer_id** 列,但我无法弄清楚 Laravel 忽略它们的原因。

  1. 我想也许输入格式不正确,但即使将 customer_id 硬编码为 1 也不起作用。 (customer_id 1 存在于客户表中)。

  2. 我还检查并确认 $request->input('customer_id') 包含正确的整数,在本例中为 1,并且确实作为记录存在客户表。

我怀疑 Laravel 忽略了相关列,但我无法弄清楚原因。

我的模型文件如下所示:

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;

class Order extends Model
{
    use Notifiable;
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'order_id', 'customer_id', 'order_status', 'customer_note', 'order_date',
    ];

    /**
     * Whether the primary key auto-increments.
     *
     * @var bool
     */
    public $incrementing = false;

    /**
     * Set the primary key.
     *
     * @var string
     */
    protected $primaryKey = ['order_id', 'customer_id'];

    protected $with = ['products']; 

    /**
     * The products that belong to the Order.
     */
    public function products()
    {
        return $this->belongsToMany('App\Product','order_product','order_id','product_id')
            ->withPivot('qty')
            ->withTimeStamps();
    }

    /**
     * The customer that belongs to the Order.
     */
    public function customer()
    {
        return $this->belongsTo('App\Customer');
    }
}

【问题讨论】:

  • 添加外键时,相关表中必须存在记录。请检查一下
  • protected $primaryKey = ['order_id', 'customer_id']; 是干什么用的?
  • @SagarGautam 请在回答之前仔细阅读我的问题。我已经解释了一切
  • @MarcusChristiansen 我已经阅读了整个问题,我只想说重新检查一下
  • @SagarGautam 是的,就像我说的,客户存在于表中。

标签: php mysql laravel eloquent


【解决方案1】:

firstOrCreate 如果无法根据您提供的属性获取行,将创建一个新的数据库条目,但不允许创建没有customer_id 的新行,因为您已在列上添加了外键而且不能是null

null 添加到您的专栏中,

$table->integer('customer_id')->unsigned()->index()->nullable();

或将firstOrCreate 更改为:

$order = Order::where('order_id', $request->input('id'))->first() ?: new Order;

【讨论】: