@@ -72,15 +72,41 @@ protected function buildDefinition(Model $model)
72
72
continue ;
73
73
}
74
74
75
- if (in_array ($ column ->dataType (), ['id ' , 'uuid ' ])) {
76
- $ foreign = $ column ->isForeignKey ();
75
+ $ foreign = $ column ->isForeignKey ();
76
+ if ($ foreign ) {
77
+ $ table = Str::beforeLast ($ column ->name (), '_id ' );
78
+ $ key = 'id ' ;
79
+
80
+ if (Str::contains ($ foreign , '. ' )) {
81
+ [$ table , $ key ] = explode ('. ' , $ foreign );
82
+ } elseif ($ foreign !== 'foreign ' ) {
83
+ $ table = $ foreign ;
84
+
85
+ if (Str::startsWith ($ column ->name (), $ foreign . '_ ' )) {
86
+ $ key = Str::after ($ column ->name (), $ foreign . '_ ' );
87
+ } elseif (Str::startsWith ($ column ->name (), Str::snake (Str::singular ($ foreign )) . '_ ' )) {
88
+ $ key = Str::after ($ column ->name (), Str::snake (Str::singular ($ foreign )) . '_ ' );
89
+ } elseif (!Str::endsWith ($ column ->name (), '_id ' )) {
90
+ $ key = $ column ->name ();
91
+ }
92
+ }
93
+
94
+ $ class = Str::studly (Str::singular ($ table ));
77
95
78
- if ($ foreign && $ foreign !== 'foreign ' ) {
79
- $ class = Str::studly (Str::singular ($ foreign ));
96
+ if ($ key === 'id ' ) {
97
+ $ definition .= self ::INDENT . "' {$ column ->name ()}' => " ;
98
+ $ definition .= sprintf ('factory(%s::class) ' , '\\' . $ model ->fullyQualifiedNamespace () . '\\' . $ class );
99
+ $ definition .= ', ' . PHP_EOL ;
80
100
} else {
81
- $ name = Str::beforeLast ($ column ->name (), '_id ' );
82
- $ class = Str::studly ($ column ->attributes ()[0 ] ?? $ name );
101
+ $ definition .= self ::INDENT . "' {$ column ->name ()}' => function () { " ;
102
+ $ definition .= PHP_EOL ;
103
+ $ definition .= self ::INDENT . ' ' . sprintf ('return factory(%s::class)->create()->%s; ' , '\\' . $ model ->fullyQualifiedNamespace () . '\\' . $ class , $ key );
104
+ $ definition .= PHP_EOL ;
105
+ $ definition .= self ::INDENT . '}, ' . PHP_EOL ;
83
106
}
107
+ } elseif (in_array ($ column ->dataType (), ['id ' , 'uuid ' ])) {
108
+ $ name = Str::beforeLast ($ column ->name (), '_id ' );
109
+ $ class = Str::studly ($ column ->attributes ()[0 ] ?? $ name );
84
110
85
111
$ definition .= self ::INDENT . "' {$ column ->name ()}' => " ;
86
112
$ definition .= sprintf ('factory(%s::class) ' , '\\' . $ model ->fullyQualifiedNamespace () . '\\' . $ class );
0 commit comments