[英]Laravel Eloquent Model many-to-many or one-to-many
I'm a little bit confused after reading Laravel
Eloquent
Model documentation. 我看完之后弄得有点
Laravel
Eloquent
模型文档。 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? hasMany()
是这种情况下的最佳解决方案,还是我需要使用其他东西?
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. hasMany()
用于一对多关系。 For Many To Many, you should use belongsToMany()
. 对于“多对多”,您应该使用
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 . 相关文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.