jeudi 22 septembre 2016

Nested relationship not returning results

I have a comments table with the following columns:

| id | user_id | post_id | parent_id | text |

Where parent_id can be a reference to a parent comment id.

In my Comment.php model, I have this relationship:

public function children()
{
    return $this->hasMany('App\Comment', 'parent_id', 'id');
}

However, when I query the table:

$comments = Comment::where('post_id', 1)
    ->where('parent_id', 0)
    ->with('children')
    ->get();

I get the following result:

[
    {
        "id":5,
        "user_id":"2",
        "post_id":"1",
        "parent_id":"0",
        "text":"Hello"
        "children":[
            {
                "id":7,
                "user_id":"1",
                "post_id":"1",
                "parent_id":"5",
                "text":"Hello"
            },
            {
                "id":9,
                "user_id":"1",
                "post_id":"1",
                "parent_id":"5",
                "text":"Hello"
            }
        ]
    },
    {
        "id":6,
        "user_id":"3",
        "post_id":"1",
        "parent_id":"0",
        "text":"Hello"
        "children":[

        ]
    }
]

You'll notice that only the top-level results (with id 5 and 6) have a "children" property, but the nested comments (id 7 and 9) don't.

How can I modify my code so that every result returns a "children" property?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire