简体   繁体   中英

Laravel 6.x Relation hasOne with key in itself

I want to create a relationship between suppliers and supplierGroup . One Supplier should have one Group. And one Group can have multiple suppliers.

The suppliers table has the key for the group in it.

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

In my supplier model I have the following:

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

and in my supplierGroup model:

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

When I then create a supplier and then a suppliergroup then they are not connected

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

The field supplier_group_id will be left empty.

Did I forgot something or did I use the relations wrong?

You should use unsignedInteger for foreign keys:

Change this:

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

To

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

Also, don't forget to set the foreign key:

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

You can use the save method to set the supplier group

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

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

To connect a supplier with a supplierGroup you have to do the following:

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

Creating doesn't work that way (it's also unnecessary).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM