【问题标题】:How to join 2 collection in query laravel如何在查询 laravel 中加入 2 个集合
【发布时间】:2021-07-19 10:57:31
【问题描述】:

我有 StudentEducation 模型,在这个模型中我得到了

public function student_education_countries()
{
    return $this->hasMany(StudentEducationCountry::class, 'education_id');
}

public function student_education_education_types()
{
    return $this->hasMany(StudentEducationEducationType::class, 'education_id');
}

在 StudentEducationCountry 模型中我得到了

public function student_education()
{
    return $this->belongsTo(StudentEducation::class, 'education_id');
}

public function student_country()
{
    return $this->belongsTo(StudentCountry::class, 'country_id');
}

在 StudentEducationEducationType 模型中我得到了

public function student_education()
{
    return $this->belongsTo(StudentEducation::class, 'education_id');
}
public function student_educationcategory()
{
    return $this->belongsTo(StudentEducationcategory::class, 'educationcategory_id');
}

问题是我应该如何加入以参加 country_id 为 2 且类型为次要的所有教育

【问题讨论】:

    标签: laravel join collections


    【解决方案1】:

    简单的 whereHas()

    $educations = StudentEducation::query()->whereHas('student_education_countries', function (Builder $query) {
        $query->where('id', 2);
    })->whereHas('student_education_education_types', function (Builder $query) {
        //maybe here you need another columns
        $query->where('type', 'secondary');
    })->get();
    

    【讨论】:

      猜你喜欢
      • 2022-01-01
      • 2021-11-22
      • 1970-01-01
      • 2016-12-15
      • 1970-01-01
      • 2018-12-09
      • 1970-01-01
      • 1970-01-01
      • 2018-06-07
      相关资源
      最近更新 更多