laravel - 未找到 morphToMany 列
问题描述
我遵循 laravel 文档中的教程,但似乎教程没有完整解释参数 morphToMany 以明确确定函数应该指向什么。
SQLSTATE [42S22]:未找到列:1054 '字段列表'中的未知列'tagables.tagables_id'(SQL:选择.
tags
*tagables
,.tagables_id
aspivot_tagables_id
, .as , .as from inner join on . = . where . = 1 and . = 应用\模型\漫画)tagables
tag_tag_id
pivot_tag_tag_id
tagables
tagables_type
pivot_tagables_type
tags
tagables
tags
tag_id
tagables
tag_tag_id
tagables
tagables_id
tagables
tagables_type
媒体表
Schema::create('media', function (Blueprint $table) {
$table->mediumIncrements('media_id)->nullable(false);
$table->string('title', 255);
});
标签表//标签内的一行(步行)
Schema::create('tags', function (Blueprint $table) {
$table->mediumIncrements('tag_id');
$table->string('tag_name', 255);
});
可标记表
Schema::create('tagables', function (Blueprint $table) {
$table->unsignedMediumInteger('tag_id')->nullable(false);
$table->unsignedMediumInteger('tagable_id')->nullable(false);
$table->string('tagable_type', 255)->nullable(false);
});
漫画模型
public function tags()
{
return $this->morphToMany(Tag::class, 'tagable');
}
漫画控制器
// insert new comic
$comic = Comic::create([
'title' => 'Doraemon',
]);
// Insert into tagables table with current comic id and bind to tag id 1
which is walking
$comic->tags->create([
'tag_id' => 1
]);
它成功插入到媒体中,但未能插入到 tagables 表中。
解决方案
我在您的代码中发现了一些错误。请尝试重写此代码。您的代码有一个工作示例。我已经为你检查过了
2021_04_10_073813_create_media_table.php
Schema::create('media', function (Blueprint $table) {
$table->id();
$table->string('name', 255);
$table->timestamps();
});
2021_04_10_073837_create_tags_table.php
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name', 255);
$table->timestamps();
});
2021_04_10_073856_create_taggables_table.php
Schema::create('taggables', function (Blueprint $table) {
$table->id();
$table->unsignedMediumInteger('tag_id')->nullable(false);
$table->unsignedMediumInteger('taggable_id')->nullable(false);
$table->string('taggable_type');
$table->timestamps();
});
class Media extends Model
{
protected $guarded = [];
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
}
class Tag extends Model
{
protected $guarded = [];
public function medias()
{
return $this->morphedByMany(Media::class, 'taggable');
}
}
最后在一些控制器中
$media = Media::create([
'name' => 'media name1',
]);
$tag = $media->tags()->create([
'name' => 'tag name1',
]);
推荐阅读
- python - Python StockTwits 发布消息
- python - NumPy - 麻烦矢量化方法
- javascript - 用 Java 脚本清理字符串
- apache-spark - 无法在 Spark 中将文件写入 Zeppelin 上的远程 hdfs
- sql - 根据值 1 和值 2 增加行号
- json - 我如何在 json 文件中观看带有 instagram url 链接的视频。它使 url 签名过期
- excel - 如何从 word-VBA 中选择/激活工作表?
- java - Maven,如何与 compile 一起运行 test-compile
- python - 如何检查文本文件的每一行是否有字符串并将所有出现该单词的行打印到新的文本文件中?
- vim - 窗口外的快速修复消息