php - Laravel belongsTo 关系不返回值
问题描述
我正在尝试运行 hasMany,但我真的不知道为什么我没有得到任何结果!两个表:公司,工作订单,每个工作订单都有一个公司名称和地址,我想在 laravel 中使用 belongsTo 关系获取
<?php
namespace App;
class Company extends Model
{
protected $table = 'company';
protected $primaryKey = 'company_id';
public function jobs() {
return $this->hasMany('App\Joborder');
}
}
我的工作订单页面
<?php
namespace App;
class Joborder extends Model
{
protected $table = "joborder";
public $primaryKey = "joborder_id";
protected $dates = [
'start_date',
'created_at',
'updated_at'
];
public function company() {
return $this->belongsTo('App\Company');
}
}
这是页面控制器:
public function joblist() {
$joblist = Joborder::all();
$newInstance = new Joborder;
$company = $newInstance->company();
dd($company->name);
dd($joblist);
return view('pages.joblist')->with('jobs',$joblist);
}
这是运行后我页面中的 dd
BelongsTo {#217 ▼
#foreignKey: "company_id"
#otherKey: "company_id"
#relation: "company"
#query: Builder {#218 ▶}
#parent: Joborder {#205 ▼
#table: "joborder"
+primaryKey: "joborder_id"
#dates: array:3 [▼
0 => "start_date"
1 => "created_at"
2 => "updated_at"
]
#guarded: array:1 [▼
0 => "id"
]
#fillable: []
#connection: null
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: []
#original: []
#relations: []
#hidden: []
#visible: []
#appends: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: false
+wasRecentlyCreated: false
}
#related: Company {#212 ▼
#table: "company"
#primaryKey: "company_id"
#guarded: array:1 [▼
0 => "id"
]
#fillable: []
#connection: null
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: []
#original: []
#relations: []
#hidden: []
#visible: []
#appends: []
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: false
+wasRecentlyCreated: false
}
}
我在公司中有 company_id 作为 pkey,在 joborder 中有 fkey 感谢您的帮助!
解决方案
你应该打电话
$company = $newInstance->company()->get();
代替
$company = $newInstance->company();
在PageController:jobList
.
现在,您不是通过相关数据来恢复关系本身。
或者,您可以company
作为属性访问,该属性应自动返回相关数据而不是关系本身:
$company = $newInstance->company;
推荐阅读
- python-3.x - 错误:无法打开 osm 文件“accesoeste.net.xml”。错误:未加载节点
- azure-data-factory-2 - Azure 数据工厂 - 使用集成运行时运行数据流
- uitableview - 这段代码背后的原因是什么导致内存泄漏,而 tableView 单元格中的 deque Cell 用于索引路径处的行
- java - servlet.service 错误,classNotFoundException
- r - 如何修复R中非数字矩阵中的错误
- swiftui - 警报视图 - 在切换结果中
- c - 数据类型范围的真正含义是什么?
- javascript - 如何在reactjs中检查以带有Route hook的短语开头的随机生成的url
- apache-spark - 在 PySpark 中的 JOIN 内创建列并用作连接键
- laravel - 删除现有的 Where 子句