【问题标题】:Laravel Eloquent "Call to undefined relationship"Laravel Eloquent “调用未定义的关系”
【发布时间】:2020-12-14 16:36:45
【问题描述】:

我正在尝试在 Laravel 中建立关系。

Survey.php:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Survey extends Model
{
    public function survey_questions()
    {
        return $this->hasMany(SurveyQuestion::class);
    }
}

还有 SurveyQuestion.php 模型:

namespace App;

use Illuminate\Database\Eloquent\Model;

class SurveyQuestion extends Model
{
    public function survey()
    {
        return $this->belongsTo(Survey::class);
    }
}

这种关系以一种方式起作用:

>>>$a = SurveyQuestion::with('survey')->get();
=> Illuminate\Database\Eloquent\Collection {#2953
     all: [
       App\SurveyQuestion {#2931
         id: 1,
         survey_id: 2,
         question_id: 1,
         survey: App\Survey {#2967
           id: 2,
           name: "Survey 2",
           created_at: "2020-08-20 18:17:45",
           updated_at: "2020-08-20 18:17:45",
           status: "active",
         },
       },
...

但在尝试其他模型时会导致错误:

>>> $a = Survey::with('survey_questions')->get();
Illuminate/Database/Eloquent/RelationNotFoundException with message 'Call to undefined relationship [survey_questions] on model [App/Survey].'

我错过了什么?蒂亚!

【问题讨论】:

    标签: laravel eloquent relationship


    【解决方案1】:

    使用提供的信息,我无法重现您的问题。事实上,它确实会返回带有问题的调查。

    >>> Survey::with('survey_questions')->get();
    => Illuminate\Database\Eloquent\Collection {#4095
         all: [
           App\Survey {#4029
             id: "1",
             created_at: "2020-08-26 00:22:23",
             updated_at: "2020-08-26 00:22:23",
             survey_questions: Illuminate\Database\Eloquent\Collection {#4103
               all: [
                 App\SurveyQuestion {#4101
                   id: "1",
                   survey_id: "1",
                   created_at: "2020-08-26 00:22:23",
                   updated_at: "2020-08-26 00:22:23",
                 },
               ],
             },
           },
         ],
       }
    
    

    您能否以 Github 存储库的形式提供一个最小的工作示例?

    【讨论】:

    • 感谢您的反馈 - 事实证明,这是用户错误和 SFTP 客户端不可靠的混合。
    猜你喜欢
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    • 2017-01-19
    • 2023-04-01
    • 2018-06-03
    • 2018-01-21
    相关资源
    最近更新 更多