如何在这个数据库模式中创建一个hasmany槽雄辩关系


How to create a hasManyTrough Eloquent relationship in this database schema?

我有以下表格

    产品
  • 变异
  • 性>项>
  • option_variant

查看这个sqlfiddle的详细信息http://sqlfiddle.com/#!2/eb1c73/24/0

我可以在我的产品模型上有这样的东西来获得所有属性,就像我在sqlfiddle查询上做的那样?

function attributes(){
return $this->hasManyThrough('Attributes','Variant');
}

谢谢! !我的模型:

<?php
class Product extends 'Eloquent {
protected $table = 'products';
public function user()
{
    return $this->belongsTo('User');
}
public function variants()
{
    return $this->hasMany('Variant');
}
public function attributes(){
    return $this->hasManyThrough('Attribute','OptionVariant');
}
}
<?php
class Variant extends 'Eloquent {
protected $table = 'variants';
public function product()
{
    return $this->belongsTo('Product');
}
public function options()
{
    return $this->belongsToMany('Option');
}
}
<?php
class Attribute extends 'Eloquent {
protected $table = 'attributes';
public function options()
{
    return $this->hasMany('Option');
}
}
<?php
class Option extends 'Eloquent {
protected $table = 'options';
public function attribute()
{
    return $this->belongsTo('Attribute');
}
public function variants()
{
    return $this->belongsToMany('Variant');
}
}
<?php
class OptionVariant extends 'Eloquent {
protected $table = 'option_variant';
}

如果您想在选择产品时获取所有属性:

Product model:

$with = ['attributes'];
在控制器:

$products = $this->product->findAll();
return View::make('products.index', compact('products'));
在视图:

@foreach($products as $product)
  {{ $product->attributes->column1 }}
@endforeach