0
votes

I have 3 tables:

  • categories
  • admins
  • users

Category can create users and admins. In categories table I have morphs field:

$table->nullableMorphs('userable');

And relations in Category model:

public function userable()
{
    return $this->morphTo();
}

public function user()
{
    return $this->morphOne(self::class, 'userable');
}

But when I tried do like this:

$category = Category::first();
$user = User::first();

$category->user()->save($user);

Get error with message:

Illuminate\Database\QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'userable_id' in 'field list' (SQL: update users set userable_id = 1, userable_type = App\Models\Category, users.updated_at = 2021-04-27 12:13:22 where id = 1)'

How I can correctly create self morph relationship in laravel?

1
Can you show us your migration?SpaceDogCS
Categories table migration? @SpaceDogCSAndreas Hunter
Oh, forget, now I understood what you're trying to doSpaceDogCS

1 Answers

0
votes

So I think that what you should be doing is adding to the User model and the Admin model the relation user you've added to the category, those models that have this relationship can be morphed into the category

class User {
    ...

    public function user() {
        return $this->morphOne(Category::class, 'userable');
    }

    ...
}


class Admin {
    ...

    public function user() {
        return $this->morphOne(Category::class, 'userable');
    }

    ...
}

so you can do your logic this way

$category = Category::first();
$user = User::first();

$user->user()->save($category);

and it will update you category record with userable_type beeing App\Models\User and userable_id beeing 1 or whatever the user id is

id name userable_type userable_id
1 Category Test App\Models\User 1

to make things easier you can create a trait and add that relationship to the trait

trait IsUserable {

    public function user() {
        return $this->morphOne(Category::class, 'userable');
    }

}

and instead of adding the relationship to User and Admin model, you just use the trait instead

class User {
    use IsUserable;
}


class Admin {
    use IsUserable;
}