【发布时间】: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