【发布时间】:2016-04-03 18:39:10
【问题描述】:
我正在使用 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]);
现在,我正在尝试在我的视图中展示这些特色产品。如果我显示Featured model 中的product_id,一切正常:
@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中)看似是一个集合,但它不起作用!
【问题讨论】:
标签: php laravel-5.2 laravel-blade table-relationships