我打算实现一个查询,以检索我所有的博客和他们的标签. 我使用的是Laravel Eloquent多态关系,但是我有一个错误是 Column not found: 1054 Unknown column 'taggables.tags_model_id' in 'field list'
. 我所有的代码在laravel和我的SQL如下。
我的表格。
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");
}
}
当我调用这个查询时,结果是一个空数组。
public function getItemsWithTags(array $attr)
{
return BlogModel::find(1)->tags;
}
非常感谢您。
Laravel的多态关系默认使用反射来确定你的关键列的名称. 因为你的模型被称为 TagModel
, Laravel假设外键为 tag_model_id
.
// Illuminate\Database\Eloquent\Model
public function getForeignKey()
{
return Str::snake(class_basename($this)).'_'.$this->getKeyName();
}
你可以通过将正确的外键显式传递给 morphedByMany
方法。
public function tags()
{
return $this->morphedByMany(TagsModel::class, 'taggable', null, 'tag_id');
}
你不能像BaseModel那样做一个中间的父类. 因为在Laravel中用属性$table是不行的,可以尝试这样做。
class BlogModel extends Model
{
use SoftDeletes;
protected $table = 'blog';
protected $primaryKey = 'id';
public function tags()
{
return $this->morphToMany(TagsModel::class,"taggable");
}
}
class TagsModel extends Model
{
use SoftDeletes;
protected $table = 'tags';
protected $primaryKey = 'id';
public function blog()
{
return $this->morphedByMany(BlogModel::class,"taggable");
}
}
试试这个例子, 你需要在你的口才方法中引用 "标签".
BlogModel::with('tags')->find(1);