Laravel Self Relationships

Developer

Well, i have this table in my Database:

CREATE TABLE categories(
id INT,
name VARCHAR,
id_parent INT,
CONSTRAINT fk_categories FOREIGN KEY(id_parent) REFERENCES categories(id)
);

In Laravel Category model, I have this:

class Category extends Eloquent
{
    protected $table = "categories";

    public function parentCategory(){
        return $this->belongsTo("Category","id_parent");
    }

    public function subCategories(){
        return $this->hasMany("Category","id_parent");
    }
}

Also I have this data:

id        name          id_parent
1         category_1    NULL
2         category_2    NULL
3         category_3    1
4         category_4    1
5         category_5    2

When I call in the controller:

count(Category::with("subCategories")->get()); The count returns 5.

And when I call in the controller:

count(Category::has("subCategories")->get()); The count returns 0.

All this is bad, because I want only the categories that parent_id = NULL, that will return to the count 3.

If I use count(Category::where("id_parent","!=","NULL") the result is 3 (it's OK), but I want to get this result by using HAS or WITH function.

So, how can I do this without using "where" function?

Sorry about my English.

Marcin Nabiałek

Assuming your errors in your code are copy-paste errors (in one places you have parent_id and in others id_parent you cannot do this using has.

It seems a bug for me because wrong query is being executed. I've created Github issue for that, I've seen at least other similar issue.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related