Laravel插入3个相关表

时间:2015-08-09 05:26:45

标签: php mysql laravel laravel-5

大家好我想知道你是否有人尝试使用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个相关表中。有人可以帮我弄这个吗。感谢

2 个答案:

答案 0 :(得分:0)

试试这个

if

答案 1 :(得分:0)

执行此代码时

$pharmacists->account()->save($account);
$pharmacy->pharmacists()->save($pharmacists);

pharmacy_id 实际上没有数据,所以这就是问题所在。因此,您应该更改 pharmacy_id 的架构,并将其值设置为 default 0

$pharmacy = Pharmacy::create([
                "name" => "Wendies Chicken",
                "address" => "My Address",                        
            ]);

$pharmacy->pharmacists()->save([
    "fname" => "Administrator",            
]);

$pharmacy->pharmacists()->account()->save([
    "username" => "root",            
]);