I use laravel eloquent with relations, I have a problem about it.
these are my eloquent models;
class Post extends BaseModel
{
public function user()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
}
class User extends BaseModel
{
public function userInfo()
{
return $this->hasOne(UserInfo::class,'user_id','id');
}
}
class UserInfo extends BaseModel
{
}
when I use the following code, the user_info is null.
$posts = Post::with(['user' => function ($query) {
$query->with(['userInfo' => function ($query) {
$query->select(['nickname','avatar']);
}]);
}])->paginate(10)
->toArray();
when i request it , the result is
{
"id": 10,
"community_id": 1,
"title": "biaoti",
"desc": null,
"content": "abc",
"user_id": 1,
"user": {
"id": 1,
"mobile_phone": "13800000003",
"user_info": null
}
}
But the following code is normall.
$posts = Post::with(['user' => function ($query) {
$query->with(['userInfo' => function ($query) {
// $query->select(['nickname','avatar']);
}]);
}])->paginate(10)
->toArray();
when i request it ,the result is :
{
"id": 10,
"community_id": 1,
"title": "biaoti",
"desc": null,
"content": "abc",
"user_id": 1,
"user": {
"id": 1,
"mobile_phone": "13800000003",
"user_info": {
"id": 1,
"user_id": 1,
"nickname": "devkang",
"avatar": "",
"birthday": "1989-01-30",
"sex": 1,
"identity": 1,
"region_id": 1
}
}
}
can you help me? I don't know how to use it, I want to select some fields from user_info.
This is happening because you exclude user_id
foreign key when you're using select
method. To fix it add foreign key to the list:
$query->select(['nickname', 'avatar', 'user_id']);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With