我与以下模型Job和Steps建立了一对多的关系。一个工作可以有很多步骤,Step属于Job。当我去查询与Job::with('steps')->find(1)
的关系时,结果会按照预期与集合
<MariasApp\Job #000000002b07ae180000000036b76e17> {
id: 1,
number: 59221,
customer_id: 5,
user_id: 17,
created_at: "2015-03-24 01:32:20",
updated_at: "2015-03-24 01:32:20",
steps: <Illuminate\Database\Eloquent\Collection #000000002b07ae070000000036b76e17> [
<MariasApp\Step #000000002b07ae7b0000000036b76e17> {
id: 37,
job_id: 1,
body: "Eligendi reiciendis ratione labore sed.",
created_at: "2015-03-24 01:32:21",
updated_at: "2015-03-24 01:32:21"
}
]
}
但是当我运行Job::with('steps')->find(1)->body
时,我得到了回复null
。我有什么方法可以从关系中拉出body
吗?
答案 0 :(得分:1)
我假设你试图从步骤集合中获取body
。您需要指定要尝试使用的步骤。要么使用第一个
Job::with('steps')->find(1)->steps->first()->body
或类似的东西来循环它们
$steps= Job::with('steps')->find(1)->steps->all();
foreach($steps as $step){
echo step->body;
}
或循环完成许多工作并获得每个工作的第一步:
$jobs = Job::with('steps')->get();
foreach($jobs as $job){
echo $jobs->steps->first()->body;
}