You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
86 lines
2.1 KiB
86 lines
2.1 KiB
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
|
|
class Category extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
protected $casts = [
|
|
'parent_id' => 'integer',
|
|
'position' => 'integer',
|
|
'priority' => 'integer',
|
|
'status' => 'integer',
|
|
'products_count' => 'integer',
|
|
];
|
|
|
|
public function translations()
|
|
{
|
|
return $this->morphMany(Translation::class, 'translationable');
|
|
}
|
|
|
|
public function scopeActive($query)
|
|
{
|
|
return $query->where('status', '=', 1);
|
|
}
|
|
|
|
public function childes()
|
|
{
|
|
return $this->hasMany(Category::class, 'parent_id');
|
|
}
|
|
|
|
public function parent()
|
|
{
|
|
return $this->belongsTo(Category::class, 'parent_id');
|
|
}
|
|
|
|
public function products()
|
|
{
|
|
return $this->hasMany(Food::class);
|
|
}
|
|
|
|
protected static function booted()
|
|
{
|
|
static::addGlobalScope('translate', function (Builder $builder) {
|
|
$builder->with(['translations' => function ($query) {
|
|
return $query->where('locale', app()->getLocale());
|
|
}]);
|
|
});
|
|
}
|
|
|
|
protected static function boot()
|
|
{
|
|
parent::boot();
|
|
static::created(function ($category) {
|
|
$category->slug = $category->generateSlug($category->name);
|
|
$category->save();
|
|
});
|
|
}
|
|
private function generateSlug($name)
|
|
{
|
|
$slug = Str::slug($name);
|
|
if ($max_slug = static::where('slug', 'like',"{$slug}%")->latest('id')->value('slug')) {
|
|
|
|
if($max_slug == $slug) return "{$slug}-2";
|
|
|
|
$max_slug = explode('-',$max_slug);
|
|
$count = array_pop($max_slug);
|
|
if (isset($count) && is_numeric($count)) {
|
|
$max_slug[]= ++$count;
|
|
return implode('-', $max_slug);
|
|
}
|
|
}
|
|
return $slug;
|
|
}
|
|
|
|
public function users()
|
|
{
|
|
return $this->morphToMany(User::class ,'visitor_log' );
|
|
}
|
|
|
|
}
|
|
|