php - 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”
任何想法我做错了什么?
解决方案
尝试改变
$testMePlease = JobStatus::first()->where('qb', '=', 1);
到
$testMePlease = JobStatus::where('qb', '=', 1)->first();
推荐阅读
- angular - 数组中的差异
.filter 签名和用法 - python - 我在编写多项选择游戏时做错了什么
- java - 在 SpringBoot 中使用 MockMvc 进行测试
- javascript - innerHTML 在窗口加载时没有改变
- r - R Shiny Dynamic 选择输入 - 捕获事件
- python-3.x - 将 DF 的某些特征应用到另一个 DF
- c++ - 获取 glVertex3f 的值并搜索最接近的值
- scala - 如何单独读取文件的每一行,以便在每一行上执行任务?- 斯卡拉
- google-sheets - 在表格中重新格式化电话号码时出现 ArrayFormula 扩展错误
- javascript - 如何编写一个名为 `add` 的函数。这样一旦它收到 2 个参数,它就会返回 2 个值的总和