I'm using Laravel 4. I have many to many relationships in my system. And I choose to use Wordpress taxonomy table scheme.
But how can I make models relationships with Laravel 4 Eloquent ORM? Here is my database tables;
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 | |
+------------------+---------------------+------+-----+---------+-------+
Normally we can do return $this->belongsToMany('Term');
but how can we do 2 relationships? We need 2 relationships first find term taxonomy from "term_taxonomy" table, after find term relations with "taxonomy_id".
And an example for how I want to use;
$categories = Post::find(1)->categories; // get terms with taxonomy="post_category"
$tags = Post::find(1)->tags; // get terms with taxonomy="post_tag"
I don't want to do this with basic database class "DB::table('table')->join('...')...
" I want to use Eloquent relation methods and models.
You can create getter methods to handle these:
In your Post model, create new methods something along the lines of:
public function getCategories()
{
return $this->hasMany()->where('taxonomy', 'post_category');
}
public function getTags()
{
return $this->hasMany()->where('taxonomy', 'post_tag');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With