【发布时间】:2020-10-15 16:07:32
【问题描述】:
我正在尝试运行 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 感谢您的帮助!
【问题讨论】:
标签: php laravel laravel-5 eloquent