2
votes

How can I change this to get only one post per user:

User::has('posts')->with('posts')->get()

$users = User::has('posts')->with(['posts', function ($query) {
    $query->first(); //->take(1)
}])->get()

This one throws an error:

"Illuminate/Database/Eloquent/RelationNotFoundException with message 'Call to undefined relationship [] on model [App/Models/User]."

User hasMany Posts is used.

2
you may create post method inside the User class and define hasOne relationship inside it, then use only User::has('post')->with('post')->get().Ersoy
That works tho!user12857969

2 Answers

0
votes

You can have post and posts relation in your model. In that way you can query one or many relationship, without doing extra.

class User
{
    // Add this instead.
    public function post()
    {

    }

    public function posts()
    {

    }
}
0
votes

You can try it:

$users = User::whereHas('posts', function ($query) {
    $query->havingRaw('COUNT(*) = 1');
})->with('posts')->get();