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?
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');
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.