Search code examples
laravelmodelrelationship

In laravel, what happen if we define hasMany() relationship but didn't define belongsTo() relationship?


I think (I don't really know, if I'm wrong please correct me), this is actually Many To Many relationship between Medias table and other tables (Users, Messages, Posts).

So, I am creating the middle table named Media_links to connect the Many To Many relation between these tables.

I am thinking to define the hasMany() relation for the Medias tables, but didn't want to define its belongsTo() relationship.

I didn't try anything yet. Posting this thread just to get insights first.


Solution

  • hasMany and belongsTo is a one-to-many, NOT many-to-many.

    about your question, you can access the relation whereever you define it, but not the inverse unless you define it!

    i.e. if you have a Teacher and Student model

    Teacher Model

    use Illuminate\Database\Eloquent\Relations\HasMany;
    
    class Teacher extends Model {
    
        public function students(): HasMany {
            return $this->hasMany(Student::class);
        }
    }
    

    Student Model

    use Illuminate\Database\Eloquent\Relations\BelongsTo;
    
    class Student extends Model {
    
        //Relation below not define.
        /* public function teacher(): BelongsTo {
            return $this->belongsTo(Teacher::class);
        } */
    }
    
    
    //each line below works fine, you can perform relationship related query 
    $teacher->students()->create([...]); // create students relation
    $teacher->students; //lazy load students relation
    Teacher::with('students')->paginate(); //eager load students relation
    
    
    //each line below will throw 500 error as Inverse relation is not define 
    $student->teacher()->create([...]); // create teacher relation
    $student->teacher; //lazy load teacher relation
    Student::with('teacher')->paginate(); //eager load teacher relation