Php 使用一对多关系时如何获取集合中的第一项

Php 使用一对多关系时如何获取集合中的第一项,php,laravel,eloquent,relationship,Php,Laravel,Eloquent,Relationship,我有点小问题,但这让我很沮丧 我有两张桌子 1.用户 2.职位 用户可以有许多帖子,帖子属于一个用户 我的问题:键入关系时如何获得第一篇帖子? public function index() { $user = User::find(1); // here it will return all posts $user->with('posts'); return view('home.index',compact('user')); } 顺便说一句:我用了闭包,但没用。

我有点小问题,但这让我很沮丧

我有两张桌子
1.用户
2.职位

用户可以有许多帖子,帖子属于一个用户

我的问题:键入关系时如何获得第一篇帖子?

public function index() {
 $user = User::find(1); 

// here it will return all posts

$user->with('posts');

    return view('home.index',compact('user'));
}
顺便说一句:我用了闭包,但没用。。。它返回所有用户的帖子

public function index()
    {

        $user = User::find(1);


        $user = $user->with(['posts' => function ($query) {
            $query->first();
        }])->get();

        return $user ;
        return view('home.index',compact('user'));
    }
结果如下:

[
{
"id": 1,
"name": "Barney Walter",
"email": "wuckert.murphy@example.org",
"created_at": "2016-12-22 10:48:45",
"updated_at": "2016-12-22 10:48:45",
"posts": []
},
{
"id": 2,
"name": "Dr. Makenzie Rutherford",
"email": "estroman@example.com",
"created_at": "2016-12-22 10:48:45",
"updated_at": "2016-12-22 10:48:45",
"posts": []
},
{
"id": 3,
"name": "Ernesto Shanahan",
"email": "pwill@example.com",
"created_at": "2016-12-22 10:48:45",
"updated_at": "2016-12-22 10:48:45",
"posts": []
},
{
"id": 4,
"name": "Rosalinda Cartwright",
"email": "josefa.murazik@example.com",
"created_at": "2016-12-22 10:48:45",
"updated_at": "2016-12-22 10:48:45",
"posts": []
},
{
"id": 5,
"name": "Kyleigh Willms",
"email": "ddach@example.net",
"created_at": "2016-12-22 10:48:45",
"updated_at": "2016-12-22 10:48:45",
"posts": [
{
"id": 1,
"user_id": 5,
"name": "Malcolm Simonis",
"title": "Autem quidem quia earum ipsam. A a commodi id adipisci quia minima iste numquam. Eum eius odit porro veniam. Et iure occaecati sapiente minima et beatae. Labore eius labore accusamus sapiente sed eveniet accusamus.",
"is_published": 1,
"created_at": "2016-12-22 10:54:14",
"updated_at": "2016-12-22 10:54:14"
}
]
}
]
有什么帮助吗。。。求你了

尝试使用
take()


而且,
orderBy('created_at','asc')
将对结果进行排序,因此您将获得第一篇帖子。

试试这个,您将只获得一篇帖子

$user = User::with('posts')->first();
$user->setRelation('posts', $business->posts->take(1));

如果您想要一个
post
的模型
对象
,而不是
集合
,那么您可以在
User
模型中定义一个新的
hasOne
关系,如下所示:

public function post()
{
    return $this->hasOne('App\Post');
}
然后您可以按以下方式查询:

$user = User::where('id', 1)->with('post')->first(); 

我不完全确定该给出什么答案,因为你的问题不清楚。预期的结果应该是什么?你想根据一篇或多篇文章筛选用户,还是只显示所有用户和他们的第一篇文章?我不太了解Laravel,但根据逻辑,我可以说你可以尝试对你的文章结果进行分页或分页查询。然后你就可以得到你需要的职位。像是的。。。我想显示具体的用户,只有他的第一篇文章?这几乎是正确的。您只需将用户模型的
first()
方法替换为
find($id)
方法。
with()
闭包在我看来很合适。
$user = User::where('id', 1)->with('post')->first();