For a Laravel application I'm working on, I would like to do something like this with my Eloquent models:
$product = Product::with('terms')->find(1);
$brand = $product->terms('brand');
$color = $product->terms('color');
The terms is a many to many relationship. Terms in this context, is terms of taxonomies. So a products terms could be: Nike, Red, Boys, etc. And if I do $product->terms
I get all terms, and when I do $product->terms('brand')
I get 'Nike' for instance.
Right now my Product model is like this:
class Product extends Eloquent {
protected $guarded = array();
public static $rules = array();
public function terms($taxonomy)
{
return $this->belongsToMany('Term', 'productterms');
}
}
Is it even possible to do what I'm trying to achieve?
Why not just use a one-to-many relationship? Have a table of colours and a table of brands and then products can have belong to a colour and brand.
If you must have many-to-many (such that a product can have multiple brands or colours) then you can have a table for colours and brands again and then use joining tables for the relationship.
This is all described in the Laravel 4 documentation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.