【发布时间】:2015-08-09 05:26:44
【问题描述】:
大家好,我想知道你们中是否有人尝试使用 3 个相关表将记录插入到 laravel 中的表中?示例
// Database Schema for Pharmacy
Schema::create('pharmacies', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('address');
});
// Relationship in App\Pharmacy table
public function pharmacists() {
return $this->hasMany('App\Pharmacist');
}
现在我有另一张桌子
Schema::create('pharmacists', function (Blueprint $table) {
$table->increments('id');
$table->integer('pharmacy_id')->unsigned()->index();
$table->foreign('pharmacy_id')->references('id')->on('pharmacies')->onDelete('cascade');
$table->string('fname');
});
// And this is the relationship in App\Pharmacist class
public function account() {
return $this->hasOne('App\Account');
}
public function pharmacy() {
return $this->belongsTo('App\Pharmacy');
}
现在是第三张桌子
// This contain the foreign key for pharmacist_id
Schema::create('accounts', function (Blueprint $table) {
$table->increments('id');
$table->integer('pharmacist_id')->unsigned()->index();
$table->foreign('pharmacist_id')->references('id')->on('pharmacists')->onDelete('cascade');
$table->string('username')->unique();
});
// This is the relationship in App\Account class
public function pharmacists() {
return $this->belongsTo('App\Pharmacist');
}
现在我尝试在 AccountsController 下使用此代码保存它
$input = Request::all();
$pharmacy = Pharmacy::create([
"name" => "Wendies Chicken",
"address" => "My Address",
]);
$pharmacists = new Pharmacist([
"fname" => "Administrator",
]);
$account = new Account([
"username" => "root",
]);
$pharmacists->account()->save($account);
$pharmacy->pharmacists()->save($pharmacists);
但我收到一个错误提示
Integrity constraint violation: 1048 Column 'pharmacist_id' cannot be null (SQL: insert into `accounts` (`username`, `pharmacist_id`, `updated_at`, `created_at`) values (root, 2015-08-09 05:13:31, 2015-08-09 05:13:31))
不知道如何保存,这只是一种保存。我想将记录保存在 3 个相关表中。有人可以帮我弄这个吗。谢谢
【问题讨论】:
标签: php mysql laravel laravel-5