Ajout relation

This commit is contained in:
Cassandre Cantet 2017-10-04 14:41:23 +02:00
parent 9d418d5623
commit c884a58025
5 changed files with 25 additions and 4 deletions

0
config/image.php Normal file → Executable file
View File

View File

View File

0
src/Exception/InvalidContent.php Normal file → Executable file
View File

View File

@ -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;
}
}