laravel 5:产品与特色产品之间的关系

时间:2016-04-03 18:39:10

标签: php laravel-5.2 laravel-blade table-relationships

我正在用Laravel 5编写一个示例电子商务网站。 我有2张桌子:

Schema::create('products', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->text('description');
    $table->float('price');
    $table->integer('category_id');
    $table->timestamps();
});

Schema::create('featureds', function (Blueprint $table) {
    $table->integer('product_id')->unique()->unsigned();
});

Schema::table('featureds', function($table) {
    $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
});

模型

class Product extends Model
{
    public function category(){
        return $this->belongsTo('App\Category');
    }    
}

class Featured extends Model
{
    public function product(){
        return $this->hasOne('App\Product', 'product_id');
    }
}

然后,我有一个Controller,我在那里拍摄了4 featured products

$featured_products = Featured::limit(4)->get();
return view('home', ['featured_products' => $featured_products]);

现在,我试图在我看来展示这些特色产品。如果我从product_id显示Featured model,一切正常:

@foreach($featured_products as $prod)
  {{$prod->product_id}}
@endforeach

但我想取名为product的名字。我试过这种方式:

@foreach($featured_products as $prod)
  @foreach($prod as $p)
    {{$p->name}}
  @endforeach
@endforeach

因为featured_products(在controller中)似乎是一个集合,但它不起作用!

1 个答案:

答案 0 :(得分:0)

Featured模型中,如果要从视图中访问关系,则在方法product()中存在关系,可以将方法名称称为属性,在这种情况下,您有名为product()的方法,因此您必须像这样调用product属性:

@foreach($featured_products as $prod)
    {{ $prod->product->name }}
@endforeach

它会根据您在模型中配置的关系自动编写product name

参考:https://laravel.com/docs/5.2/eloquent-relationships

编辑:

对不起我的不好,我猜你定义了一个错误的关系,你的Product模型应该有featured()方法使用hasOne关系,而Featured模型应该使用product()关系使用belongsTo方法。所以在你App\Featured模型中,你必须定义这样的关系:

return $this->belongsTo('App\Product');

在你的App\Product模型中,你应该像这样定义关系:

return $this->hasOne('App\Featured');

希望它有效