Laravel - How to setup a morphOne relationship

ⅰ亾dé卋堺 提交于 2019-12-09 18:58:52

问题


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?

So far I have this

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();
    }
}

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();
});

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?


回答1:


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();
    }
}

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


来源:https://stackoverflow.com/questions/43771242/laravel-how-to-setup-a-morphone-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!