I'm facing issue in one to one polymorphic relationship in laravel 6.0.
I have 2 Model CategoryModel and SeoModel(Polymorphic model with one to one relationship)
Below is a snippet from controller where i try to add category and its seo's.
$info=[];
$query = [
'name' => 'name',
'description' => 'description',
'parent_id' => NULL,
'status' => 1,
'image' => NULL,
'sort_order' => 1,
];
// dd($query);
$info["category"]= new CategoryModel;
$info["seo"] = new SeoModel;
$info['category']->fill($query);
$info['category']->save();
$seo_query = [
'meta_title' => 'meta_title',
'meta_description' => 'meta_description',
'meta_keyword' => 'meta_keyword',
'seoable_id' => $info['category']->getKey(),
'seoable_type' => CategoryModel::class,
];
// dd($seo_query);
$info['category']->seo()->create($seo_query);
$info['category_id']= $info['category']->getKey();
return $info;
SeoModel Path : App/Models/Seo/SeoModel
class SeoModel extends Model
{
use SoftDeletes, ModelTrait;
protected $table = 'seo';
protected $primaryKey = 'id';
protected $fillable = ['meta_title', 'meta_description', 'meta_keyword', 'seoable_id', 'seoable_type'];
protected $dates = ['deleted_at'];
public $incrementing = false;
public function seoable()
{
return $this->morphTo();
}
}
CategoryModel Path : App/Models/Category/CategoryModel
namespace App\Models\Category;
use App\Models\Seo\SeoModel;
use App\Traits\ModelTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Log;
class CategoryModel extends Model
{
use SoftDeletes, ModelTrait;
protected $table = 'category';
protected $primaryKey = 'category_id';
protected $fillable = ['name', 'description', 'parent_id', 'status', 'image', 'sort_order'];
protected $dates = ['deleted_at'];
protected $with = ['seo'];
protected $appends = ['image_url'];
protected $file_directory = "categories/";
public function getImageUrlAttribute() {
return $this->resolveFileUrl($this->attributes['image']);
}
public function seo(){
return $this->morphOne(SeoModel::class, 'seoable');
}
}
Thanks in Advance
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire