【问题标题】:find() and with() return all models, instead of model with childrenfind() 和 with() 返回所有模型,而不是带有孩子的模型
【发布时间】:2016-02-22 04:43:22
【问题描述】:

我有一个模型 Survey,它在模型 ScaleQuestions 中定义了相关的子记录。

我想创建一条路线,让我可以查看单个调查并查看其所有子量表问题。我创建了这条路线,试图急切加载一项调查及其所有子项:但它返回所有调查模型:

    public function survey($id) {
        $survey = \App\Gt\Lib\Survey::find($id)
            ->with('scale_questions')
            ->get();
        ;
       \dump($id);
        \dump($survey);
        return view('gt/admin/survey')->with('survey',$survey);

(目前)有 43 个调查,只有 10 个儿童规模问题,但转储清楚地告诉我它加载了 43 个调查。

Collection {#684 ▼
  #items: array:43 [▼
    0 => Survey {#208 ▶}
    1 => Survey {#209 ▶}
    2 => Survey {#210 ▶}
    3 => Survey {#211 ▶}

当我取出get() 时,我得到一个构建器对象,我不知道如何处理:

Builder {#161 ▼
  #query: Builder {#154 ▶}
  #model: Survey {#165 ▶}
  #eagerLoad: array:1 [▶]
  #macros: []
  #onDelete: null
  #passthru: array:10 [▶]
}

这似乎是一个未处理的查询,因为我无法从中获取任何属性:

public function survey($id) {
    $survey = \App\Gt\Lib\Survey::find($id)
        ->with('scale_questions');
        \dump($survey->id);

给我这个:

ErrorException in AdminSurveysController.php line 31: Undefined property: Illuminate\Database\Eloquent\Builder::$id

如何快速加载单个调查及其子问题?

【问题讨论】:

    标签: eloquent eager-loading


    【解决方案1】:

    我需要最后做find()

    $survey = \App\Gt\Lib\Survey::with('scale_questions')->find($id);
    

    【讨论】:

      猜你喜欢
      • 2016-11-18
      • 2018-06-30
      • 1970-01-01
      • 2020-04-15
      • 1970-01-01
      • 2013-08-25
      • 1970-01-01
      • 2021-04-13
      • 1970-01-01
      相关资源
      最近更新 更多