简体   繁体   English

Laravel Eloquent'with'有空洞的结果

[英]Laravel Eloquent 'with' has empty result

I am working on a small API based on Laravel 5.3 passport ( https://laravel.com/docs/5.3/passport ). 我正在开发基于Laravel 5.3护照的小型API( https://laravel.com/docs/5.3/passport )。

After Googling a lot I didn't find an answer yet to my problem. 谷歌搜索后我没有找到答案我的问题。 I got the following function that has to retrieve the people I follow from the database. 我得到了以下功能,必须从数据库中检索我关注的人。 This is working great. 这很有效。 After that I need to grab all friends statuses from the DB with the user info, drink info, file info and toast info. 之后,我需要从数据库中获取所有朋友状态,包括用户信息,饮料信息,文件信息和烤面包信息。 This also works great. 这也很有效。 It isn't working when file or toast or drink is empty. 当文件或烤面包或饮料为空时它不起作用。 I get an empty array back. 我得到一个空阵列。

The function: 功能:

public function index(Request $request)
{
    $user = $request->user();

    $friends = Follow::with(['user'])->where('follows_user_id', '=', $user->id)->get();

    foreach ($friends as $friend) {

        $status = Status::with(['user', 'drink', 'file', 'toast'])->where(
            'user_id', '=', $friend->id
        )->CreatedAtDescending()->get();

    }

    if (!isset($status) || empty($status)) {
        return response(['message' => 'Nothing found.'], 404);
    }

    return $status;
}

How can I get the result back, even when the drink or file or toast is empty? 即使饮料或文件或烤面包是空的,我怎样才能得到结果?

I got it working! 我搞定了! The solution is: 解决方案是:

public function index(Request $request)
{
    $user = $request->user();

    $friends = Follow::with(['user'])->where('follows_user_id', '=', $user->id)->get();

    foreach ($friends as $friend) {

        $status = Status::with(['user' => function ($query) use ($friend) {
            $query->where('id', '=', $friend->following_user_id);
        }, 'drink', 'file', 'toast'])->get();
    }

    if (!isset($status) || empty($status)) {
        return response(['message' => 'Nothing found.'], 404);
    }

    return $status;
}

It where just some small issues in the query. 它只是查询中的一些小问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM