Subversion-Projekte lars-tiefland.webanos.faltradxxs.de

Revision

Revision 2 | Blame | Vergleich mit vorheriger | Letzte Änderung | Log anzeigen | RSS feed

<?php

    namespace App\Models;

    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\Relations\BelongsTo;
    use Illuminate\Database\Eloquent\Relations\HasMany;
    use Illuminate\Support\Facades\Cache;
    use Spatie\Sluggable\HasSlug;
    use Spatie\Sluggable\SlugOptions;

    class Item extends Model
    {
        use HasFactory, HasSlug;

        /**
         * Get the options for generating the slug.
         */
        public function getSlugOptions(): SlugOptions
        {
            return SlugOptions::create()
                ->generateSlugsFrom( 'name' )
                ->saveSlugsTo( 'slug' )
                ->usingLanguage( 'de' )
                ->doNotGenerateSlugsOnUpdate()
                ->skipGenerateWhen( function ()
                {
                    return $this->directory_id < 0;
                } );
        }

        function medium(): HasMany
        {
            return $this->hasMany( ItemMedium::class )->orderBy( "rank" );
        }

        public function price(): HasMany
        {
            return $this->hasMany( Price::class )->where("preis","!=",0)->orderBy( "preis_index" );
        }

        public function manufacturer(): BelongsTo
        {
            return $this->belongsTo( Manufacturer::class );
        }

        // On the Model class add the following method.

        public function resolveRouteBinding( $value, $field = null ): ?Model
        {
            $cacheName = "item_" . $value;

            if ( Cache::has( $cacheName ) )
            {
                return Cache::get( $cacheName );
            }

            $result = $this->with( 'price', 'medium.medium', 'manufacturer' )->where( 'slug', $value )->firstOrFail();
            Cache::put( $cacheName, $result, 86400 );

            return $result;
        }
    }