我正在使用laravel 5.4,我有一个品牌表和一个产品表,我的关系是这样的:
class Product extends Model
{
protected $table = 'products';
public function brand()
{
return $this->belongsTo(Brand::class);
}
}
和
class Brand extends Model
{
public function products()
{
return $this->hasMany(Product::class);
}
}
我的迁移:
Schema::create('brands', function (Blueprint $table) {
$table->increments('id');
$table->string('name',15)->unique();
$table->string('tag',15)->unique();
$table->mediumInteger('numofads')->unsigned()->default(0);
$table->timestamps();
});
&安培;
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->integer('brand_id')->unsigned();
$table->foreign('brand_id')->references('id')->on('brands')->onDelete('cascade');
$table->string('name',15)->unique();
$table->string('tag',15)->nullable()->unique();
$table->mediumInteger('numofads')->unsigned()->default(0);
$table->timestamps();
});
在我的控制器中,我将采用3个品牌并将其发送到视图中:
public function show()
{
$brands = Brand::take(3)->get();
return view('show',compact('brands'));
}
在我看来,我会重复一遍,只展示这样的产品:
@foreach($brands as $brand)
{{ $brand->products->name }}
@endforeach
我认为一切正常但我会得到错误:
ErrorException in Collection.php line 1543:
Property [name] does not exist on this collection instance. (View: /home/k1/Laravel/carsan/resources/views/welcome.blade.php)
答案 0 :(得分:4)
$brand->products
将成为Collection
。你将不得不迭代它。它不是单一模型,它可能包含许多模型,就像$brands
是一组模型一样。
@foreach ($brands as $brand)
...
@foreach ($brand->products as $product)
...
@endforeach
@endforeach