Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel eloquent with in with select return null

Tags:

laravel

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.

like image 621
devkang Avatar asked Nov 26 '17 16:11

devkang


1 Answers

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']);
like image 83
Alexey Mezenin Avatar answered Oct 21 '22 22:10

Alexey Mezenin