skip to Main Content

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.

3

Answers


  1. Nothing really happens to your application, other than if you were to access you’r pivot table, you won’t be able to call any relationships from it.

    Login or Signup to reply.
  2. If you are creating pivot table you should create a belongsToMany relation , this provides you sync(), attach() methods . Otherwise you can simply create hasMany relation. What you are trying to do actually ?

    Login or Signup to reply.
  3. 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 IlluminateDatabaseEloquentRelationsHasMany;
    
    class Teacher extends Model {
    
        public function students(): HasMany {
            return $this->hasMany(Student::class);
        }
    }
    

    Student Model

    use IlluminateDatabaseEloquentRelationsBelongsTo;
    
    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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search