我想使用 Laravel 5 Eloquent Relationship 创建实例。
我有 2 个迁移和 2 个 Eloquent 模型。
公司迁移:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCompaniesTable extends Migration {
public function up()
{
Schema::create('Companies', function(Blueprint $table)
{
$table->string('CompanyCode', 15);
$table->string('Name', 200);
$table->string('Type', 100);
$table->tinyInteger('IsActive')->default(1);
$table->timestamps();
$table->primary('CompanyCode');
});
}
public function down()
{
Schema::drop('Companies');
}
}
公司模式:
namespace App\Models\Setting\Organization;
use Illuminate\Database\Eloquent\Model;
class Company extends Model {
protected $fillable = ['CompanyCode', 'Name', 'Type'];
public function organizationUnits(){
return $this->hasMany('App\Models\Setting\Organization\OrganizationUnit', 'CompanyCode');
}
}
组织单位迁移:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateOrganizationUnitsTable extends Migration {
public function up()
{
Schema::create('OrganizationUnits', function(Blueprint $table)
{
$table->string('OrganizationUnitCode', 15); //PK
$table->string('CompanyCode', 15); //FK
$table->string('Name', 200);
$table->tinyInteger('IsActive')->default(1);
$table->timestamps();
$table->primary('OrganizationUnitCode');
$table->foreign('CompanyCode', 'OrgUnits_Company_FK')
->references('CompanyCode')
->on('Companies')
->onDelete('cascade');
});
}
public function down()
{
Schema::drop('OrganizationUnits');
}
}
组织单元模型:
namespace App\Models\Setting\Organization;
use Illuminate\Database\Eloquent\Model;
class OrganizationUnit extends Model {
protected $table = "OrganizationUnits";
protected $fillable = ['OrganizationUnitCode', 'CompanyCode', 'Name'];
public function company(){
return $this->belongsTo('App\Models\Setting\Organization\Company', 'CompanyCode');
}
}
关系是一个Company可以有一个或多个OrganizationUnit,一个OrganizationUnit必须有一个且只能有一个Company。
我尝试使用以下代码在 php artisan tinker
中创建 OrganizationUnit 的新实例:
$company = \App\Models\Setting\Organization\Company::first();
$orgunit = $company->organizationUnits()->create(['OrganizationUnitCode' => 'abcdef']);
但是 Laravel 给出了以下错误:
Illuminate\Database\QueryException with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'CompanyCode' cannot be null (SQL: insert into `OrganizationUnits` (`Org anizationUnitCode`, `CompanyCode`, `updated_at`, `created_at`) values (abcdef, , 2015-12-17 00:17:33, 2015-12-17 00:17:33))'
我哪里错了?请帮忙。我是 Laravel 新手。
最佳答案
它明确表示 CompanyCode 不能为空。您可以手动定义它,也可以在创建迁移时在蓝图实例上使用 increments
方法。
关于php - Laravel 从 ManyToOne 关系错误 SQLSTATE [23000] 创建 Eloquent 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34318243/