mus*_*usa 5 php relationship laravel eloquent laravel-4
我正在使用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 | | |
+------------+---------------------+------+-----+---------+----------------+
Run Code Online (Sandbox Code Playgroud)
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 | |
+------------------+---------------------+------+-----+---------+----------------+
Run Code Online (Sandbox Code Playgroud)
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 | |
+------------------+---------------------+------+-----+---------+-------+
Run Code Online (Sandbox Code Playgroud)
通常情况下我们可以做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"
Run Code Online (Sandbox Code Playgroud)
我不想用基本的数据库类做这个" DB::table('table')->join('...')..."我想使用Eloquent关系方法和模型.
您可以创建 getter 方法来处理这些:
在您的 Post 模型中,创建类似于以下内容的新方法:
public function getCategories()
{
return $this->hasMany()->where('taxonomy', 'post_category');
}
public function getTags()
{
return $this->hasMany()->where('taxonomy', 'post_tag');
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1436 次 |
| 最近记录: |