L5 |关系修补程序查询

L5 | Relationship Tinker Query

我已经与以下模型 Job 和 Steps 建立了一对多关系。一个job可以有很多step,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 吗?

我假设您正在尝试从步骤集合中获取 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;
}