laravel 5.6 fill() 尝试使用不存在的 'id' 字段更新表

标签 laravel eloquent

这是我的模型

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class OrganizationProfile extends Model
{
    protected $fillable = [
    'logo', 
    'number_of_employees', 
    'siup', 'npwp', 'year_established', 'join_ppsdm', 'industry_sector',
    'address', 'city', 'province', 'country', 
    'postal_code',
    'organization_phone', 
    'organization_email'
];
}

OrganizationProfile 的迁移表

Schema::create('organization_profiles', function (Blueprint $table) {
        $table->unsignedInteger('organization_id');
        $table->primary('organization_id');
        $table->foreign('organization_id')->references('id')->on('organizations')->onDelete('cascade');
        $table->string('logo')->nullable();
        $table->integer('number_of_employees')->nullable();
        $table->string('siup')->nullable();
        $table->string('npwp')->nullable();
        $table->integer('year_established')->nullable();
        $table->integer('join_ppsdm')->nullable();
        $table->string('industry_sector')->nullable();
        $table->text('address')->nullable();
        $table->string('city')->nullable();
        $table->string('province')->nullable();
        $table->string('country')->nullable();
        $table->string('postal_code')->nullable();
        $table->string('organization_phone')->nullable();
        $table->string('organization_email')->nullable();
        $table->text('meta')->nullable();
        $table->timestamps();
    });

这在我的 Controller 中:

$org = OrganizationProfile::where('organization_id', $id)->first();

    if ($org == null) {
        $org = new OrganizationProfile();
        $org->organization_id = $id;
    } 
    $org->fill($request->input())->save();

这是错误: enter image description here

eloquent 尝试使用“id”作为引用来更新更改的值。我没有“id”字段,我有一个“organization_id”作为主键和外键。如果我不更改 $fillable 中列出的任何值,则不会显示此错误。

提前致谢

最佳答案

Eloquent 会假设每个表都有一个名为 id 的主键列。您可以使用 $primaryKey 覆盖它,如下所示:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class OrganizationProfile extends Model
{
    protected $primaryKey = 'organization_id';
}

关于laravel 5.6 fill() 尝试使用不存在的 'id' 字段更新表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50001034/

相关文章:

php - Laravel - 使用子查询创建模型

php - 使用路由闭包中的 Controller 命名空间

php - 如何在 blade.php 中使用 vue 获取字段的旧值

php - 模型上的 SoftDeletes 会破坏动态属性

laravel - 如何在laravel Eloquent 查询中获取前10个类别列表

php - 在 Laravel 4 中将变量从路由组传递到路由函数

php - 如何在 Laravel 中使用 Eloquent Relationship 在 View 中显示两个表数据

php - 根据所选类别选择帖子

php - UPDATE query form while循环,代码很慢

php - Laravel 模型事件保存未触发