【问题标题】:Laravel Eloquent 'with' has empty resultLaravel Eloquent 'with' 的结果为空
【发布时间】:2017-04-22 20:21:34
【问题描述】:

我正在开发一个基于 Laravel 5.3 护照 (https://laravel.com/docs/5.3/passport) 的小型 API。

在谷歌上搜索了很多之后,我还没有找到我的问题的答案。 我得到了以下函数,它必须从数据库中检索我关注的人。这很好用。之后,我需要使用用户信息、饮料信息、文件信息和吐司信息从数据库中获取所有朋友的状态。这也很好用。当文件或吐司或饮料为空时,它不起作用。我得到一个空数组。

功能:

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;
}

即使饮料、文件或吐司是空的,我如何才能取回结果?

【问题讨论】:

    标签: php laravel api orm eloquent


    【解决方案1】:

    我搞定了!解决办法是:

    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;
    }
    

    它只是查询中的一些小问题。

    【讨论】:

      猜你喜欢
      • 2021-10-26
      • 2018-01-11
      • 2021-04-02
      • 1970-01-01
      • 2017-04-01
      • 2013-05-27
      • 2020-07-09
      • 1970-01-01
      • 2021-01-26
      相关资源
      最近更新 更多