drcvvkx914772 2015-05-14 13:48
浏览 49
已采纳

Laravel Eloquent一对多

I have two Models, Company and Jobs. A Company can have many Jobs.

Job Model:

class Job extends \Eloquent {

    public function company() {
        return $this->belongsTo('Company');
    }
}

Company Model:

class Company extends \Eloquent {

    public function jobs() {
        return $this->hasMany('Job');
    }
}

If I do the following, I want the $job object to have both the job & company objects in the same way I would if I did a SQL join such as:

SELECT * FROM  `jobs` JOIN company ON `company_id` = company.id WHERE jobs.`id` = 156;

Instead, if I do this

$job = Job::find($id);
var_dump($job);
exit;

$job has only the job.

If I do this:

$job = Job::find($id)->company;
var_dump($job);
exit;

I only get the company.

How do I get $job to be the equivalent of the SQL join?

  • 写回答

1条回答 默认 最新

  • doumu6941 2015-05-14 14:04
    关注

    You should be able to use the ->with() function of Laravel to return the model job and it's associated model company:

    $job = Job::with("company")->find($id);
    

    You should then be able to access all fields in the job model like you normally would:

    $job->field_1; 
    $job->field_2; 
    ...
    

    AND also the company model's fields:

    $job->company->field_1;
    $job->company->field_2;
    ...
    

    I'm not 100% familiar with its usage in Laravel 5, but any further information can be found here:

    Laravel Documentation - Eager Loading

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里