Laravel-如何建立morphOne关系 [英] Laravel - How to setup a morphOne relationship
问题描述
我正在尝试为类别实现可变形表,现在我具有以下内容.
I'm trying to implement a morphable table for categories, right now I've the following.
// Snippet Table
- id
- title
- body
// Post Table
- id
- title
- body
// Category Table
- id
- name
我希望能够将帖子和摘录变形为仅具有一个类别,如下所示:
I want to be able to morph the posts and snippets to have only one category, something like this:
// Categorizable Table
- category_id
- categorizable_id
- categorizable_type
此分类表是否需要其他模型?还是有一种无需其他模型即可设置的方法?
Do I have to have another model for this categorizable table? Or there is a way to set it without another model?
到目前为止,我有这个
class Snippet extends Model
{
public function category()
{
return $this->morphOne(Category::class, 'categorizable');
}
}
class Post extends Model
{
public function category()
{
return $this->morphOne(Category::class, 'categorizable');
}
}
class Category extends Model
{
public function categorizable()
{
return $this->morphTo();
}
}
我有4个表,分别是snippets
,posts
,categories
,categorizables
,最后一个迁移看起来像这样.
And I have 4 tables, snippets
, posts
, categories
, categorizables
, the last one the migration looks like this.
Schema::create('categorizables', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('category_id');
$table->morphs('categorizable');
$table->timestamps();
});
问题是,保存此关系的正确方法是什么,我在修补程序上对其进行了测试,并且attach($category_id)
和sync($category_id)
均未保存该关系,因此它们返回错误BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::categorizable()'
,我该怎么办?想念吗?
The thing is, what is the correct way to save this relationship, I'm testing it on tinker and bothattach($category_id)
and sync($category_id)
aren't saving the relationship they return the error BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::categorizable()'
, What I'm missing?
推荐答案
对不起,我认为您想要多对多关系. morphOne
关系API与morphMany相同. >文档
Sorry I thought you wanted many-to-many relationship. morphOne
relationship API is the same as morphMany
from the docs
Post extends Model
{
public function category() {
return $this->morphOne(Category::class, 'categorizable');
}
}
Category extends Model
{
public function categorizable() {
return $this->morphTo();
}
}
编辑
使用morphOne时,不需要删除数据透视表categorizables
表并更改categories
表以包括morph字段
EDIT
When using morphOne you don't need a pivot table categorizables
table must be deleted and change your categories
table to include the morph fields
// Category Table
- id
- name
- categorizable_id
- categorizable_type
这篇关于Laravel-如何建立morphOne关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!