Php Laravel:无法检索一对多camelCase方法

Php Laravel:无法检索一对多camelCase方法,php,laravel,eloquent,Php,Laravel,Eloquent,我试图检索一对多关系的反方向,其中方法是camelCase。i、 e 拥有阶级:OneToMany class Brand extends Model { public function products() { return $this->hasMany(Product::class); } } 自有类 class Product extends Model { public function MyBrand() {

我试图检索一对多关系的反方向,其中方法是camelCase。i、 e

拥有阶级:OneToMany

class Brand extends Model
{
    public function products()
    {
        return $this->hasMany(Product::class);
    }
}
自有类

class Product extends Model
{
    public function MyBrand()
    {
        return $this->belongsTo(Brand::class);
    }
}
$product = Product::find(1);
$brand = $product->my_brand;
dd($brand->name);
像这样检索反向相关模型:

class Product extends Model
{
    public function MyBrand()
    {
        return $this->belongsTo(Brand::class);
    }
}
$product = Product::find(1);
$brand = $product->my_brand;
dd($brand->name);
错误,尝试获取非对象的属性“name”

我也试过:

$brand = $product->myBrand;
它不起作用

但是,如果我将我的方法设置为如下所示,它将起作用:

public function brand()
{
    return $this->belongsTo(Brand::class);
}
问题是:当方法在CameCase中时,如何使其工作?

试试这个

 public function my_brand()
{
    return $this->belongsTo(Brand::class);
}
把这种关系称为

$product = Product::find(1);
$brand = $product->my_brand;
dd($brand->name);

在关系中指定其外键

class Product extends Model
{
   public function MyBrand()
   {
      return $this->belongsTo(Brand::class,'brand_id');
      //brand_id is foreign key in your product table
   }
}

$product = Product::find(1)->with('MyBrand'); //But it will be good to eager load it
$product->MyBrand->name; //It will definitely return name now

您需要更改brand()中的方法name,因为Elounce将自动确定Brands表中正确的外键列

如果要将其保留为MyBrand(),则需要指定外键:

public function MyBrand()
   {
      return $this->belongsTo(Brand::class,'product_id');
   }

从未尝试过,但可能是类似于
$product->\u my\u brand
。如果您将该方法重命名为
myBrand
,那么它将被称为
$product->myu brand
,您可以这样访问名称:dd($product->brand->name)。你也可以这样做:dd($product->brand);嗨,MihaiMatei。我试过了。它不起作用了。你错过了阅读问题。此$product->brand->name仅在方法名为brand时有效。我说的是当您
dd($brand)
它返回什么时,使用一个camCase方法名,即公共函数MyBrand()。这是一条信息:试图获取非objectWhat value hold$brand veriable的属性“name”?检查dd($品牌);我不清楚你在问什么?请您先用dd($brand)检查$brand变量的值$product=product::find(1)$品牌=$product->my_品牌;dd(品牌);我认为它将返回空值。由于这个原因,您将得到这个错误