首页 > 解决方案 > Laravel hasMany to Belongs 返回 undefined

问题描述

我知道以前有人问过这个问题,但具体到我的情况,我找不到有效的答案。

目前我有两个模型。应用\工作状态应用\客户

在模型 App\JobStatus 我有这个:

public function customer()
{
  return $this->belongsTo('App\Customer');
}

在模型 App\Customer 我有这个:

public function jobs()
{
    return $this->hasMany('App\JobStatus', 'customer_id');
}

'customer_id' 是外键。然后我尝试从我的控制器中的 Jobstatus 访问客户,如下所示:

$testMePlease = JobStatus::first()->where('qb', '=', 1);
$testMePlease->customer;

我试图 dd 这个。把它放在 foreach 循环中。我也试过 $testMePlease->customer->customer_name。Customer_name 是表中的一列,我得到相同的错误:“未定义的属性:Illuminate\Database\Eloquent\Builder::$customer”

任何想法我做错了什么?

标签: phplaravellaravel-5eloquent

解决方案


尝试改变

$testMePlease = JobStatus::first()->where('qb', '=', 1);

$testMePlease = JobStatus::where('qb', '=', 1)->first();

推荐阅读