I am going to implement a query that retrieves all my blogs with their tags. I am using Laravel Eloquent polymorphic relations but I have an error that is Column not found: 1054 Unknown column 'taggables.tags_model_id' in 'field list'
. All my codes in both laravel and my SQL are presented below:
my tables:
create table tags
(
id int auto_increment
primary key,
name varchar(200) null,
created_at timestamp default CURRENT_TIMESTAMP not null,
updated_at timestamp null,
deleted_at timestamp null
);
create table taggables
(
id int auto_increment
primary key,
tag_id int null,
taggable_type varchar(512) null,
taggable_id int null,
created_at timestamp default CURRENT_TIMESTAMP not null,
updated_at timestamp null,
deleted_at timestamp null,
constraint fk23
foreign key (tag_id) references tags (id)
on update cascade on delete cascade
);
create index taggables_tag_id_index
on taggables (tag_id);
create table blog
(
id int auto_increment
primary key,
title varchar(200) null,
passage text null,
author varchar(200) null,
category varchar(200) null,
img_url varchar(200) null,
created_at timestamp default CURRENT_TIMESTAMP not null,
updated_at timestamp null,
deleted_at timestamp null,
user_id int not null,
category_id int null,
constraint fk18
foreign key (user_id) references users (id)
on update cascade on delete cascade,
constraint fk19
foreign key (category_id) references blog (id)
on update cascade on delete cascade
);
create index blog_index
on blog (category_id);
create index blog_users_index
on blog (user_id);
Eloquent Models
class BaseModel extends Model
{
protected $table;
protected $primaryKey;
use SoftDeletes;
}
class BlogModel extends BaseModel
{
protected $table = 'blog';
protected $primaryKey = 'id';
public function tags()
{
return $this->morphToMany(TagsModel::class,"taggable");
}
}
class TagsModel extends BaseModel
{
protected $table = 'tags';
protected $primaryKey = 'id';
public function blog()
{
return $this->morphedByMany(BlogModel::class,"taggable");
}
}
when I called this query the result is an empty array
public function getItemsWithTags(array $attr)
{
return BlogModel::find(1)->tags;
}
thank you very much.
Laravel's polymorphic relations use reflection, by default, to determine the name of your key columns. Because your model is called TagModel
, Laravel assumes that the foreign key will be tag_model_id
.
// Illuminate\Database\Eloquent\Model
public function getForeignKey()
{
return Str::snake(class_basename($this)).'_'.$this->getKeyName();
}
You can fix this by explicitly passing the correct foreign key to the morphedByMany
method:
public function tags()
{
return $this->morphedByMany(TagsModel::class, 'taggable', null, 'tag_id');
}