许多人在口若悬河与分类多对多关系(Many to many relationships with t

2019-08-31 10:02发布

我使用Laravel 4.我有很多在我的系统中的许多关系。 我选择使用WordPress的分类表方案。

但是,我怎么能做出与Laravel 4雄辩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('...')... ”我想用雄辩的关系的方法和模型。

Answer 1:

您可以创建getter方法来处理这些:

在安置自己的模式,创造新方法的线沿线的东西:

public function getCategories()
{
    return $this->hasMany()->where('taxonomy', 'post_category');
}

public function getTags()
{
    return $this->hasMany()->where('taxonomy', 'post_tag');
}


文章来源: Many to many relationships with taxonomy in Eloquent