Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 获取只有一篇文章的用户_Laravel_Laravel 7 - Fatal编程技术网

Laravel 获取只有一篇文章的用户

Laravel 获取只有一篇文章的用户,laravel,laravel-7,Laravel,Laravel 7,如何更改此设置以使每个用户仅获得一篇帖子: User::has('posts')->with('posts')->get() $users = User::has('posts')->with(['posts', function ($query) { $query->first(); //->take(1) }])->get() 这一个抛出一个错误: “Illumb/Database/Elount/RelationNotFoundExceptio

如何更改此设置以使每个用户仅获得一篇帖子:

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

$users = User::has('posts')->with(['posts', function ($query) {
    $query->first(); //->take(1)
}])->get()
这一个抛出一个错误:

“Illumb/Database/Elount/RelationNotFoundException,消息为“调用模型[App/Models/User]上未定义的关系[]。”


用户使用了许多帖子。

您可以在模型中拥有
post
Posts
关系。通过这种方式,您可以查询一个或多个关系,而无需执行额外的操作

类用户
{
//加上这个。
公共职能职位()
{
}
公共职能职位()
{
}
}
您可以尝试:

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

您可以在User类中创建
post
方法,并在其中定义
hasOne
关系,然后仅使用
User::has('post')->with('post')->get()
。这样就可以了!