netdjw
netdjw

Reputation: 6007

Laravel Eloquent Model many-to-many or one-to-many

I'm a little bit confused after reading Laravel Eloquent Model documentation. So I have this database structure:

task
   id
   name
   description

tag
   id
   name

task_tag
   id
   task_id
   tag_id

One task may has zero, one or many tags. Of course one tag may has connection to zero, one or many tasks.

I tried this, but not sure:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Task extends Model {
    public function tags() {
        return $this->hasMany('App\Tag');
    }
}

hasMany() is the best solution in this case or I need to use something else?

Upvotes: 0

Views: 303

Answers (1)

jackel414
jackel414

Reputation: 1686

What you're describing sounds like a typical many-to-many relationship (including the pivot table you've outlined). hasMany() is intended to be used in One To Many relationships. For Many To Many, you should use belongsToMany(). So your Task model would look like:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    public function tags()
    {
        return $this->belongsToMany('App\Tag');
    }
}

Relevant docs.

Upvotes: 2

Related Questions