[英]how to get the first item in the collection when using one-to-many relationship
I have a little problem but it's frustrating me a lot. 我有一个小问题,但这让我很沮丧。
I have two tables 我有两张桌子
1. users 1.用户
2. posts 2.帖子
The user can have many posts and the post belongs to one user 该用户可以有多个帖子,而该帖子属于一个用户
My question : how to get the first post when typing the relation? 我的问题:键入关系时如何获得第一篇文章?
public function index() {
$user = User::find(1);
// here it will return all posts
$user->with('posts');
return view('home.index',compact('user'));
}
By the way : i used closure but it didn't work ... it return all users with posts 顺便说一句:我用了闭包,但是没用...它返回所有有帖子的用户
public function index()
{
$user = User::find(1);
$user = $user->with(['posts' => function ($query) {
$query->first();
}])->get();
return $user ;
return view('home.index',compact('user'));
}
and the result is like that : 结果是这样的:
[
{
"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"
}
]
}
]
any help about that ... please !! 关于这个的任何帮助...请!
Try to use take()
: 尝试使用
take()
:
$user = User::with(['posts' => function ($query) {
$query->orderBy('created_at', 'asc')->take(1);
}])->first();
And orderBy('created_at', 'asc')
will sort result, so you'll take the very first post. 并且
orderBy('created_at', 'asc')
将对结果进行排序,因此您将撰写第一篇文章。
Try this you will get just 1 post. 试试这个,你只会得到1个帖子。
$user = User::with('posts')->first();
$user->setRelation('posts', $business->posts->take(1));
If you want a model object
of post
instead of collection
then you can define a new hasOne
relation in User
model as: 如果要
post
而不是collection
的模型object
,则可以在User
模型中将新的hasOne
关系定义为:
public function post()
{
return $this->hasOne('App\Post');
}
And then you can query it as: 然后您可以查询为:
$user = User::where('id', 1)->with('post')->first();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.