【问题标题】:ErrorException Trying to get property 'name' of non-object in Hasmany relationshipErrorException 试图在 Hasmany 关系中获取非对象的属性“名称”
【发布时间】:2021-04-15 19:25:24
【问题描述】:

您好,我正在尝试通过 HasMany 关系访问车辆品牌并收到属性错误,我该如何解决?

迁移

车辆

Schema::create('vehicles', function (Blueprint $table) {
            $table->id();
            $table->integer('year');
            $table->string('color');
            $table->timestamps();
        });

品牌

  Schema::create('brands', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->foreignId('vehicles_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
            $table->timestamps();
        });

型号

车辆

 public function Brands()
    {
        return $this->BelongsTo(Brand::class,'vehicles_id');
    }

品牌

 public function Vehicles()
    {
        return $this->hasMany(Vehicle::class,'vehicles_id');
    }

方法

 $V = Vehicle::find($id);
       dd($V->Brands->name);

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    你的关系不正确。 在您当前的代码中,一个品牌 (BMW) 只能附加到一辆车上。但实际上却是另一种方式。车辆属于一个品牌,但一个品牌可以拥有多个车辆。

    只是翻转关系

    Schema::create('vehicles', function (Blueprint $table) {
        $table->id();
        $table->integer('year');
        $table->string('color');
        $table->foreignId('brand_id')->constrained()->onUpdate('cascade')->onDelete('cascade');;
        $table->timestamps();
    });
    

    外键应在车辆表中

    车辆属于品牌

    // Models/Vehicle.php
    
    // singular, because vehicle belong only to one Brand
    public function brand()  
    {
        return $this->belongsTo(Brand::class);
    }
    

    品牌有很多车型

    // Models/Brand.php
    
    // plural because one Brand has many vehicles
    public function vehicles()
    {
        return $this->hasMany(Vehicle::class,'vehicles_id');
    }
    

    然后在你的控制器中:

    $vehicle = Vehicle::with('brand')->find($id);
    dd($vehicle->brand->name);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-10
      • 2019-08-24
      • 2020-09-28
      • 2017-08-02
      • 2018-04-14
      • 2019-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多