Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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?

like image 215
Big Boss Avatar asked Dec 10 '22 11:12

Big Boss


1 Answers

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
like image 160
yazfield Avatar answered Jan 06 '23 05:01

yazfield