To create a self-referential relationship in Eloquent, you can use a "many-to-many" relationship with a pivot table. This is useful when you want to associate a contract with other contracts. Here's how you can set it up:
-
Create a Pivot Table:
First, create a migration for the pivot table. This table will store the associations between contracts.
php artisan make:migration create_contract_contract_table --create=contract_contractIn the migration file, define the table structure:
Schema::create('contract_contract', function (Blueprint $table) { $table->id(); $table->foreignId('contract_id')->constrained('contracts')->onDelete('cascade'); $table->foreignId('related_contract_id')->constrained('contracts')->onDelete('cascade'); $table->timestamps(); });Run the migration:
php artisan migrate -
Define the Relationship in the Model:
In your
Contractmodel, define a many-to-many relationship to itself:use Illuminate\Database\Eloquent\Model; class Contract extends Model { public function relatedContracts() { return $this->belongsToMany(Contract::class, 'contract_contract', 'contract_id', 'related_contract_id'); } }This method
relatedContractswill allow you to access all contracts related to a given contract. -
Using the Relationship:
You can now use this relationship to associate contracts with each other:
// Assuming you have two contract instances $contract1 = Contract::find(1); $contract2 = Contract::find(2); // Attach a related contract $contract1->relatedContracts()->attach($contract2->id); // Retrieve related contracts $relatedContracts = $contract1->relatedContracts;
This setup allows you to associate contracts with each other using a pivot table, similar to a many-to-many relationship. You can attach, detach, and sync related contracts as needed.