laravel eloquent 关系无效

laravel eloquent relations not working

我正在使用 laravel 5.4,我有一个品牌 table 和一个产品 table,我的关系是这样的:

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)

$brand->products 将成为 Collection。你将不得不迭代它。它不是单个模型,它可能包含许多模型,就像 $brands 是模型的集合。

@foreach ($brands as $brand)
    ...
    @foreach ($brand->products as $product)
        ...
    @endforeach
@endforeach