一般你会为您的实体,您可以在其中指定关系的创建模型:
class Product extends Eloquent
{
protected $table = 'products';
public function attributes()
{
return $this->belongsToMany('Attribute', 'products_attributes');
}
}
class Attribute extends Eloquent
{
protected $table = 'attributes';
public function products()
{
return $this->belongsToMany('Product', 'products_attributes');
}
}
的belongsToMany()
方法建立了一个多到多的关系。第一个参数指定相关的模型类名,第二个参数指定保存两个实体之间连接的数据库表的名称。
要找到ID为1234的产品,你会喜欢这个取,
$product = Product::find(1234);
然后,您可以神奇地访问其所有属性是这样的:
$attributes = $product->attributes;
欲了解更多信息,请可以参考the documentation。
我会小心的,因为Eloquent使用内部'protected $ attributes = array();'这很可能会破坏这个。 – tomzx