Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jamesmarsh43's avatar

Eloquent Relationships

Hi all, I have a query regarding relationships.

I have two tables:

students:
id
student_number
name
etc.......
assessments:
id,
student_id,
criteria 1,
criteria 2,
etc.......

I am using the model to create the relationship:

Model - Student:

public function assessments() {
        return $this->hasMany(Assessment::class);
    }

Model - Assessment:

public function student(){
    return $this->belongsTo(Student::class);
    }

This works well, however I would like to add a relationship from Student to a third table. The difficulty is that the third table exists already.

Table

assessment2:
id,
student,
name,
criteria 1,
criteria 2,
etc.......

assessment2.student and students.student_number are the same values.

In the models I have tried the following without success:

Model - Student:

public function assessments2() {
        return $this->hasMany(Assessment2::class, 'student');
    }

Model - Assessment2:

public function student(){
    return $this->belongsTo(Student::class, 'student_number');
    }

any ideas appreciated.

Thanks James.

0 likes
6 replies
bugsysha's avatar
bugsysha
Best Answer
Level 61
return $this->belongsTo(Student::class, 'student', 'student_number');

// and

return $this->hasMany(Assessment2::class, 'student', 'student_number');
jamesmarsh43's avatar

Thanks for the answer and it now works a treat for all fields except created_at

ErrorException (E_ERROR)
Unexpected data found

is this because both tables have the same column name??

is there a way around this??

Thanks again James.

jamesmarsh43's avatar

Please ignore the last comment, I worked it out.

As the table assessment2 is imported data, I had to change the date column type to varchar.

I assume that eloquent was looking for date/time stamp in the query due to the column name being "created_at".

I changed the column name to "created" and all is now working.

Thanks for your help with the original question.

jdubwelch's avatar

Do your tables have timestamps?

If you do the expectation is that they are called created_at and updated_at. If your timestamp fields are called something different then you can set the different name by adding this to the model:

const CREATED_AT = 'creation_date';
const UPDATED_AT = 'last_update';

If you do not have timestamps in the table, then you can turn them off in the model by doing:

public $timestamps = false;

For more info, go here and search for "timestamps". https://laravel.com/docs/6.x/eloquent

Please or to participate in this conversation.