Laravel 关系在与获取数据一起使用时返回 null

问题描述 投票:0回答:1

我有两个表: class_list 、 Teacher_detail 我尝试使用关系从两个表中获取数据,我可以正确获取class_list数据,但是当我使用with()获取teacher_detail数据时,它将返回null。

如何获取教师详细数据?

类列表模型

  protected $fillable = [
        'CLASS_NAME',
        'IMG_SRC',
        'TEACHER_ID',
        'DESCRIBE',
        'START_DATE',
        'CLASS_WEEK_DAY',
        'START_TIME',
        'END_TIME',
        'CREATETIME',
        'CREATOR',
        'LASTUPDATE',
        'MODIFIER'
      ];

      public $primaryKey = 'id';

      protected $dateFormat = 'Y-m-d';

      public $timestamps = false;

      protected $table = 'class_list';
      public function teacherElement(){
        return $this->belongsTo(TeacherDetailModel::class,'teacher_id','id')->select(['id','name','graduated_school']);
      }

教师详细模型

  protected $fillable = [
    'NAME',
    'GRADE_SCHOOL',
    'EXPERTISE',
    'EMAIL',
    'CREATETIME',
    'CREATOR',
    'LASTUPDATE',
    'MODIFIER'
  ];

  public $primaryKey = 'id';

  protected $dateFormat = 'Y-m-d';

  public $timestamps = false;

  protected $table = 'TEACHER_DETAIL';
  public function ClassListModelHasMany(){
    return $this->hasMany(ClassListModel::class,'id','teacher_id');
  }

使用关系

  public function show(Request $request)
    {
        //
        $post = $request->post();
        $detail = ClassListModel::where("class_list.id","=",$post['body']['ID'])
                  ->with('teacherElement')
                  ->get();
        return $detail;
    }

foreignId 受限

    Schema::table('TEACHER_DETAIL', function (Blueprint $table) {
      $table->foreignId('id')->constrained('USER', 'id');
    });
    Schema::table('CLASS_LIST', function (Blueprint $table) {
      //
      $table->foreignId('TYPE_ID')->constrained('CLASS_TYPE', 'id');
      $table->foreignId('TEACHER_ID')->constrained('TEACHER_DETAIL','id');
    });

返回值(teacher_element 为 null) enter image description here

我删除了teacherElement中的选择,但它仍然不起作用

php laravel eloquent
1个回答
0
投票

你的关系不正确。

将其更改为开启

TeacherDetailModel
:

 public function ClassListModelHasMany(){
    return $this->hasMany(ClassListModel::class,'teacher_id','id');
  }

也可以像这样更改查询:

    $detail = ClassListModel::where('id',$post['body']['ID'])
                  ->with('teacherElement')
                  ->get();
    return $detail;
© www.soinside.com 2019 - 2024. All rights reserved.