我正在使用Laravel 4.我的系统中有很多关系。我选择使用Wordpress分类表方案。
但是如何与Laravel 4 Eloquent ORM建立模型关系?这是我的数据库表;
terms
:+------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------------------+------+-----+---------+----------------+
| term_id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(200) | NO | MUL | | |
| slug | varchar(200) | NO | UNI | | |
+------------+---------------------+------+-----+---------+----------------+
term_taxonomy
:+------------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+---------------------+------+-----+---------+----------------+
| term_taxonomy_id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| term_id | bigint(20) unsigned | NO | MUL | 0 | |
| taxonomy | varchar(32) | NO | MUL | | |
| description | longtext | NO | | NULL | |
| parent | bigint(20) unsigned | NO | | 0 | |
| count | bigint(20) | NO | | 0 | |
+------------------+---------------------+------+-----+---------+----------------+
term_relationships
:+------------------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------------+---------------------+------+-----+---------+-------+
| object_id | bigint(20) unsigned | NO | PRI | 0 | |
| term_taxonomy_id | bigint(20) unsigned | NO | PRI | 0 | |
| term_order | int(11) | NO | | 0 | |
+------------------+---------------------+------+-----+---------+-------+
通常情况下,我们可以return $this->belongsToMany('Term');
,但我们怎样才能做到2个关系?在找到与“taxonomy_id”的术语关系之后,我们需要2个关系首先从“term_taxonomy”表中找到术语分类。
我想要如何使用的一个例子;
$categories = Post::find(1)->categories; // get terms with taxonomy="post_category"
$tags = Post::find(1)->tags; // get terms with taxonomy="post_tag"
我不想用基本的数据库类“DB::table('table')->join('...')...
”做这个。我想使用Eloquent关系方法和模型。
答案 0 :(得分:2)
您可以创建getter方法来处理这些:
在Post模型中,按照以下方式创建新方法:
public function getCategories()
{
return $this->hasMany()->where('taxonomy', 'post_category');
}
public function getTags()
{
return $this->hasMany()->where('taxonomy', 'post_tag');
}