我正在使用 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 关系?我们需要 2 个关系,首先从“term_taxonomy”表中找到术语分类,然后找到与“taxonomy_id”的术语关系。
还有一个我想如何使用的例子;
$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 关系方法和模型。