如何在此数据库模式中创建hasManyTrough Eloquent关系?

时间:2014-06-17 20:08:43

标签: php mysql laravel eloquent

我有以下表格

  • 产品
  • 变种
  • attributes
  • 选项
  • 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';
}

1 个答案:

答案 0 :(得分:1)

如果您想要选择产品的所有属性:

在产品型号中:

$with = ['attributes'];

在控制器中:

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

在视图中:

@foreach($products as $product)
  {{ $product->attributes->column1 }}
@endforeach
相关问题