Code?
Oct 9, 2024
11
Level 2
Get the primary key from table using belongsTo
I hav a following class code:
Student
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
use HasFactory;
protected $fillable = [
'name',
'email',
'academic_registration',
'created_at',
'updated_at'
];
protected $table = 'students';
}
StudentDisciplineClassroom (The Pivot table)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class StudentDisciplineClassroom extends Model
{
use HasFactory;
protected $fillable = [
'student',
'ra',
'discipline',
'classroom',
'created_at',
'updated_at'
];
protected $table = 'students_disciplines_classrooms';
public function studentRelation(): BelongsTo
{
return $this->belongsTo(Student::class, 'ra', 'academic_registration');
}
...
}
I need to do this works
public function studentRelation(): BelongsTo {
return $this->belongsTo(Student::class, 'ra', 'academic_registration');
}
The problem:
'academic_registration' in Student::class is not the primary key of table and i need get the prymary key (id) this
Then i tryed
$all = $sdc::select('ra')->with('studentRelation')->where('classroom',$request->classroom)->distinct('student')->get();
but studentRelation just returns null
Please or to participate in this conversation.