[英]Laravel Create Eloquent Instance from ManyToOne Relationship Error SQLSTATE[23000]
我想使用Laravel 5 Eloquent Relationship創建實例。
我有2個遷移和2個雄辯的模型。
公司遷移:
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');
}
}
OrganizationUnits遷移:
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');
}
}
OrganizationUnit模型:
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');
}
}
關系是:一個公司可能擁有一個或多個OrganizationUnit,一個OrganizationUnit必須擁有一個且只有一個Company。
我試圖使用以下代碼在php artisan tinker
創建OrganizationUnit的新實例:
$company = \App\Models\Setting\Organization\Company::first();
$orgunit = $company->organizationUnits()->create(['OrganizationUnitCode' => 'abcdef']);
但是Laravel給出以下錯誤:
帶有消息'SQLSTATE [23000]的Illuminate \\ Database \\ QueryException:違反完整性約束:1048列'CompanyCode'不能為空(SQL:插入到'OrganizationUnits`(“ Org anizationUnitCode`,`CompanyCode`,`updated_at`,`created_at` )值(abcdef,,2015-12-17 00:17:33,2015-12-17 00:17:33))'
我哪里做錯了? 請幫忙。 我是Laravel的新手。
明確指出CompanyCode不能為null。 您可以手動定義它,也可以在創建遷移時在Blueprint實例上使用increments
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.