From 20655eabbf8013462207a2a828d20f8af530d40c Mon Sep 17 00:00:00 2001 From: Rahul Dey Date: Thu, 14 May 2020 23:01:40 +0530 Subject: [PATCH] added Polymorphic Relationship --- src/Generators/ModelGenerator.php | 17 +++++++++++++++-- src/Lexers/ModelLexer.php | 3 +++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/Generators/ModelGenerator.php b/src/Generators/ModelGenerator.php index ccf59a2a..ca00e0de 100644 --- a/src/Generators/ModelGenerator.php +++ b/src/Generators/ModelGenerator.php @@ -146,9 +146,22 @@ private function buildRelationships(Model $model) $name = Str::beforeLast($name, '_id'); $class = Str::studly($class ?? $name); - $relationship = sprintf("\$this->%s(%s::class)", $type, '\\' . $model->fullyQualifiedNamespace() . '\\' . $class); - $method_name = $type === 'hasMany' || $type === 'belongsToMany' ? Str::plural($name) : $name; + if($type === 'morphTo') { + $relationship = sprintf("\$this->%s()", $type); + }elseif($type === 'morphMany' || $type === 'morphOne') { + $relation = Str::of($name)->lower()->singular().'able'; + + $relationship = sprintf("\$this->%s(%s::class, '%s')", $type, '\\' . $model->fullyQualifiedNamespace() . '\\' . $class, $relation); + }else { + $relationship = sprintf("\$this->%s(%s::class)", $type, '\\' . $model->fullyQualifiedNamespace() . '\\' . $class); + } + + if( $type === 'morphTo' ){ + $method_name = Str::of($model->name())->lower()->singular().'able'; + }else { + $method_name = $type === 'hasMany' || $type === 'belongsToMany' || $type === 'morphMany' ? Str::plural($name) : $name; + } $method = str_replace('DummyName', Str::camel($method_name), $template); $method = str_replace('null', $relationship, $method); diff --git a/src/Lexers/ModelLexer.php b/src/Lexers/ModelLexer.php index 333cda7f..7c96aede 100644 --- a/src/Lexers/ModelLexer.php +++ b/src/Lexers/ModelLexer.php @@ -12,6 +12,9 @@ class ModelLexer implements Lexer 'belongsto' => 'belongsTo', 'hasone' => 'hasOne', 'hasmany' => 'hasMany', + 'morphone' => 'morphOne', + 'morphmany' => 'morphMany', + 'morphto' => 'morphTo', 'belongstomany' => 'belongsToMany' ];