i have two table: class_list 、 teacher_detail i try to use relationship to get data from two table, i can get class_list data correctly but when i use with() to get teacher_detail data, it will return null.
how can i get teacher_detail data?
ClassListModel
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']);
}
TeacherDetailModel
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');
}
use relationship
public function show(Request $request)
{
//
$post = $request->post();
$detail = ClassListModel::where("class_list.id","=",$post['body']['ID'])
->with('teacherElement')
->get();
return $detail;
}
foreignId constrained
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');
});
return Value(teacher_element is null) enter image description here
i delete select in teacherElement but it still not work
your relation is incorrect.
change it to on
TeacherDetailModel:also can change query like this: