【问题标题】:Eloquent model's relationsEloquent 模型的关系
【发布时间】:2019-09-20 21:25:02
【问题描述】:

我正在开发一个简单的调查系统,但在获取正确数据时遇到了问题。

我正在尝试检索分配给特定调查的所有包含问题和答案的类别。

ERD:

以下代码几乎可以正常工作,但它不会过滤分配给特定调查的问题。

$categories = Category::whereHas('questions.surveys', function ($query) use ($id) {
    $query->where('surveys.id', $id); 
})->with('questions', 'questions.answers', 'questions.surveys')
->get();

问题模型:

class Question extends Model
{
    public function answers() 
    {
        return $this->belongsToMany('App\Models\Surveys\Answer', 'question_answers');
    }

    public function category() 
    {
        return $this->belongsTo('App\Models\Surveys\Category');
    }

    public function surveys() 
    {
        return $this->belongsToMany('App\Models\Surveys\Survey', 'survey_questions');
    }
}

类别模型:

class Category extends Model
{
    public function questions() 
    {
        return $this->hasMany('App\Models\Surveys\Question');
    }
}

调查模型

class Survey extends Model
{
    public function questions() 
    {
        return $this->belongsToMany('App\Models\Surveys\Question', 'survey_questions');
    }
}

【问题讨论】:

  • 您可以记录查询以查看发生了什么吗? stackoverflow.com/questions/41140975/…
  • 我建议您安装 Laravel 调试工具栏 (github.com/barryvdh/laravel-debugbar),因为它会显示运行的 RAW sql 查询。这很可能可以帮助您缩小问题的范围。但是,我认为问题与 whereHas('questions.surveys') 有关。如果我没记错的话,这个参数应该是一个模型函数。所以应该是“问题”,然后你把 where 放在 $query->surveys()->where('surveys.id', $id);

标签: php laravel eloquent


【解决方案1】:

为此,您还需要constrain your eager loads

$categories = Category::with([
    'questions' => function ($query) use ($id) {
        $query->with('answers', 'surveys')
            ->whereHas('surveys', function ($query) use ($id) {
                $query->where('id', $id);
            });
    },
])->whereHas('questions.surveys', function ($query) use ($id) {
    $query->where('id', $id);
})->get();

这样您的意思是只获取与特定调查相关的类别,并且只获取与该类别和特定调查相关的问题。

【讨论】:

    猜你喜欢
    • 2015-10-29
    • 2016-02-26
    • 2014-11-22
    • 2021-10-01
    • 2018-10-20
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 2016-08-19
    相关资源
    最近更新 更多