首页 > 解决方案 > Laravel Eloquent 中两个表的连接结果错误?

问题描述

我目前正在尝试在多个表之间建立关系。

教育机构

id  institution_name  country  city    
1    ABC College       UK      London

用户教育

id  user_id  institution_id  grade   year  
1    1         1              3.2    2010

关系是

class UserEducation extends Model {

  public function educationInstitution()
    {
       return $this->hasMany(EducationInstitution::class,'institution_id');
    }
}

class EducationInstitution extends Model{

   public function userEducation()
    {
        return $this->hasMany(UserEducation::class);
    }
}

最后在控制器中:

class UserEducationController extends Controller
{
    public function getUserEducation()
    {
        $userEducation = UserEducation::with('education_institutions')
            ->where('user_id',auth()->user()->id)
            ->orderBy('created_at', 'desc')
            ->get();


        return response()->json([
            'userEducation' => $userEducation
        ]);
    }
}

它给出以下错误:

调用模型 [App\Models\UserEducation] 上的未定义关系 [education_institutions]。

我期待着这样的回应:

{
  "userEducation": [
    {
      "id": 1,
      "user_id": 1,
      "institution_id": 1,
      "grade": "3.49",
      "institution_name": "ABC College"
      "country":"UK",
      "city":"London"
    }
}

如何解决?

标签: laraveleloquentlaravel-7

解决方案


好吧,正如@Eahiya 所说,我的关系中有一点错误。此外,我更正::with('educationInstitution')了@Sumit 的建议。

我目前的代码是:

class UserEducation extends Model {

  public function educationInstitution()
    {
       return $this->belogsTo(EducationInstitution::class,'institution_id');
    }
}

class EducationInstitution extends Model{

   public function userEducation()
    {
        return $this->hasMany(UserEducation::class);
    }
}

和控制器:

public function getUserEducation()
    {
        $userEducation = UserEducation::with('educationInstitution')
            ->where('user_id',auth()->user()->id)
            ->orderBy('created_at', 'desc')
            ->get();


        return response()->json([
            'userEducation' => $userEducation
        ]);
    }

它现在工作正常。


推荐阅读