php - 未找到列:1054 未知列“字段列表”中的“taggables.tags_model_id”laravel 雄辩
问题描述
我将实现一个查询来检索我所有的博客及其标签。我正在使用 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);
雄辩的模型
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');
}
推荐阅读
- vba - 将对话中的旧电子邮件移至子文件夹
- outlook - Outlook iOS App 显示发件人图标甚至按钮。如何?
- java - 如何使应用程序变暗和变亮主题?
- react-native - 对于反应原生应用程序,有没有办法在生产中查看 console.log 输出?
- python-3.x - 有哪些选项可以处理从 pdf 中提取的文本以删除文本换行/对齐效果
- javascript - 在javascript中返回承诺
- pandas - 在我提交熊猫拉取请求之前如何记录“whatsnew”-rst 错误修复
- python - 如何将 n 维 numpy 数组切割成给定大小的块
- r - 如何在 R Shiny 中的数据表中更改为 24 小时格式
- javascript - 为什么我在使用 OAuth2 身份验证时在 heroku 上收到 redirect_uri_mismatch 错误?