簡體   English   中英

Laravel 6.x 關系 hasOne 本身帶有密鑰

[英]Laravel 6.x Relation hasOne with key in itself

我想在supplierssupplierGroup組之間建立關系。 一個供應商應該有一個集團。 一個集團可以有多個供應商。

suppliers表中包含組的鍵。

$table->integer("supplier_group_id")->nullable();

在我的supplier model 中,我有以下內容:

public function supplierGroup(){
        return $this->belongsTo(SupplierGroup::class);
    }

在我的supplierGroup組 model 中:

public function supplier(){
        return $this->hasMany(Supplier::class);
    }

然后當我創建供應商和供應商組時,它們沒有連接

$supplier = \App\Models\Suppliers\Supplier::create([]);
$group = $supplier->supplierGroup()->create([]);

字段supplier_group_id _組_id 將留空。

我是忘記了什么還是我使用了錯誤的關系?

您應該使用unsignedInteger作為外鍵:

改變這個:

$table->integer("supplier_group_id")->nullable();

$table->unsignedInteger("supplier_group_id")->nullable();

另外,不要忘記設置外鍵:

$table->foreign('supplier_group_id')->reference('id')->on('supplier_groups');

可以使用save方法設置供應商組

$supplierGroup = new \App\Models\Suppliers\SupplierGroup()

$supplier->supplierGroup()->save($supplierGroup);

要將suppliersupplierGroup組連接,您必須執行以下操作:

$group = \App\Models\Suppliers\SupplierGroup::create([]);
        $supplier = \App\Models\Suppliers\Supplier::create([]);
        $supplier->supplierGroup()->associate($group)->save();

創建不是那樣工作的(這也是不必要的)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM