From c884a58025aa1e61bdf2933ded3c7d4e0eba61d3 Mon Sep 17 00:00:00 2001 From: Cassandre Cantet Date: Wed, 4 Oct 2017 14:41:23 +0200 Subject: [PATCH] Ajout relation --- config/image.php | 0 ...2017_10_03_135933_create_images__table.php | 0 ...7_10_03_140902_create_associate_images.php | 0 src/Exception/InvalidContent.php | 0 src/Model/Image.php | 29 ++++++++++++++++--- 5 files changed, 25 insertions(+), 4 deletions(-) mode change 100644 => 100755 config/image.php mode change 100644 => 100755 database/migrations/2017_10_03_135933_create_images__table.php mode change 100644 => 100755 database/migrations/2017_10_03_140902_create_associate_images.php mode change 100644 => 100755 src/Exception/InvalidContent.php diff --git a/config/image.php b/config/image.php old mode 100644 new mode 100755 diff --git a/database/migrations/2017_10_03_135933_create_images__table.php b/database/migrations/2017_10_03_135933_create_images__table.php old mode 100644 new mode 100755 diff --git a/database/migrations/2017_10_03_140902_create_associate_images.php b/database/migrations/2017_10_03_140902_create_associate_images.php old mode 100644 new mode 100755 diff --git a/src/Exception/InvalidContent.php b/src/Exception/InvalidContent.php old mode 100644 new mode 100755 diff --git a/src/Model/Image.php b/src/Model/Image.php index 6bbe1fe..d554019 100755 --- a/src/Model/Image.php +++ b/src/Model/Image.php @@ -3,6 +3,7 @@ namespace Meoran\Images\Model; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\MorphToMany; use Intervention\Image\Exception\NotReadableException; use Meoran\Images\Exception\InvalidContent; use Spatie\ImageOptimizer\OptimizerChain; @@ -142,14 +143,34 @@ class Image extends Model return true; } + /** + * @param Model $class + * @param $relationName + * @return MorphToMany + */ + public static function createRelation(Model $class, $relationName) { + + $instance = $class->newRelatedInstance(self::class); + + $foreignKey = 'relation_id'; + $relatedKey = 'image_id'; + $name = 'relation'; + $table = 'associate_images'; + $inverse = false; + + $relation = new MorphToMany( + $instance->newQuery(), $class, $name, $table, + $foreignKey, $relatedKey, $relationName , $inverse + ); + $relation->withPivot('position'); + + return $relation; + } + public function toArray() { $attributes = parent::toArray(); - if (isset($attributes['pivot']) && array_key_exists('position', $attributes['pivot'])) { - $attributes['position'] = $attributes['pivot']['position']; - } - unset($attributes['pivot']); return $attributes; } }