Skip to content

Defining parent using manual attribute assignment not working #336

Closed
@antonkomarev

Description

@antonkomarev

If you will redefine parent_id with getParentIdName() method then attribute assignment will be ignored.

class Category
{
    public function getParentIdName()
    {
        return 'parent_category_id';
    }
}

This wouldn't work:

$shop->categories()->create([
    'parent_category_id' => $parentCategory->getKey(),
    'title' => 'Title',
]);

But this will work:

$shop->categories()->create([
    'parent_id' => $parentCategory->getKey(),
    'title' => 'Title',
]);

I've tested another one approach, and it's working:

$category = $shop->categories()->create([
    'title' => 'Title',
]);

$category->appendToNode($parentCategory)->save();

But as you can see it's +1 query. And there is no easy way to create factory in tests:

I have to do:

$subcategories = factory(Category::class, 2)->make();
$subcategories->get(0)->appendToNode($category)->save();
$subcategories->get(1)->appendToNode($category)->save();

Instead of:

$subcategories = factory(Category::class, 2)->create([
    'parent_category_id' => $category->getKey(),
]);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions