Reputation: 6007
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
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');
}
}
Upvotes: 2