@@ -43,7 +43,7 @@ public function primary(string $name = 'id'): self
4343 }
4444
4545 /**
46- * Adds an integer column with a foreign key relationship to another table.
46+ * Adds an integer column with a foreign key relationship to another table. This is an alias to `foreignId`.
4747 *
4848 * **Example**
4949 * ```php
@@ -69,13 +69,43 @@ public function belongsTo(string $local, string $foreign, OnDelete $onDelete = O
6969 return $ this ;
7070 }
7171
72+ /**
73+ * Adds an integer column with a foreign key relationship to another table.
74+ *
75+ * **Example**
76+ * ```php
77+ * new CreateTableStatement('orders')
78+ * ->foreignId('customer_id', constrainedOn: 'customers');
79+ * ```
80+ * ```php
81+ * new CreateTableStatement('orders')
82+ * ->foreignId('orders.customer_id', constrainedOn: 'customers.id');
83+ * ```
84+ *
85+ * @param string $local The local column in the format `[this_table.]foreign_id`.
86+ * @param string $constrainedOn The foreign table in the format `other_table[.id]`.
87+ */
88+ public function foreignId (string $ local , string $ constrainedOn , OnDelete $ onDelete = OnDelete::RESTRICT , OnUpdate $ onUpdate = OnUpdate::NO_ACTION , bool $ nullable = false ): self
89+ {
90+ if (! str_contains ($ local , '. ' )) {
91+ $ local = $ this ->tableName . '. ' . $ local ;
92+ }
93+
94+ if (! str_contains ($ constrainedOn , '. ' )) {
95+ $ constrainedOn = $ constrainedOn . '.id ' ;
96+ }
97+
98+ return $ this ->belongsTo ($ local , $ constrainedOn , $ onDelete , $ onUpdate , $ nullable );
99+ }
100+
72101 /**
73102 * Adds a foreign key constraint to another table.
74103 *
75104 * **Example**
76105 * ```php
77- * $table->integer('customer_id', nullable: false);
78- * $table->foreignKey('orders.customer_id', 'customers.id');
106+ * new CreateTableStatement('orders')
107+ * ->integer('customer_id', nullable: false)
108+ * ->foreignKey('orders.customer_id', 'customers.id');
79109 * ```
80110 *
81111 * @param string $local The local column in the format `this_table.foreign_id`.
0 commit comments