Illuminate/Eloquent: 如何在构造函数中使用 belongsTo

Illuminate/Eloquent: how to use belongsTo in constructor

我想提供当前模型中 "foreign key table" 的数据。

我目前正在通过函数 (getBrand) 实现这一点。

但现在我想将其作为 属性 访问。所以我添加了一个属性($brand),想通过在模型的构造函数中调用函数(getBrand)来填充它。

class Car extends Eloquent {
  public $brand;

  public function __construct() {
    parent::__construct();
    $this->brand = getBrand();
  }

  public function getBrand() {
    return $this->belongsTo('App\Brand', 'FK_BrandId')->first()->Brandname;
  }
}

但这会在构造函数的执行过程中产生错误:

Trying to get property of non-object

有什么解决办法吗?谢谢!

您可以将 getBrand 函数稍微更改为以下内容,以定义 CarBrand 之间的 relationship:

 public function brand() {
    return $this->belongsTo('App\Brand', 'FK_BrandId');
 }

然后可以从 Car 的实例访问品牌模型,例如$car->brand。要访问品牌名称,您可以使用 $car->brand->Brandname.

如果您想直接访问品牌名称,您可以在 Car 模型上定义一个 "accessor",如下所示:

public function getBrandNameAttribute()
{
    return $this->brand->BrandName;
}

然后您可以使用 $car->brand_name 访问品牌名称。