dotelauv682684 2017-09-20 07:27
浏览 116
已采纳

Laravel Eloquent查询模型与关系

I have 2 models with a relationship Company and DamageReport.

A DamageReport is always linked to a Company by the key company_id.

So company_id in DamageReport equals id in Company.

Very simple, right? Now my goal is to query the Company when I know the id of the DamageReport.

For example

I have a row of the DamageReport table:

id company_id

6  1

And the record of Company with id is:

id name

1  Company 1

So in my controller I have the DamageReport id (6) and need to query company with id 1.

I've set up a relationship like this in my models

Company model:

/**
 * The Damage Reprots that belong to the Company.
 */
public function damageReports()
{
    return $this->belongsToMany('App\DamageReport');
}

DamageReport model:

/**
 * The company of a damagereport
 *
 */
public function company()
{
    return $this->belongsTo('App\Company');
}

Now in my controller I tried something like this but I honestly have no clue

$company = new Company;

$company = $company->company($damageReportId);

dd($company);
  • 写回答

3条回答 默认 最新

  • dpl74687 2017-09-20 07:50
    关注

    Your relationship is wrong.

    It should be

    Company model:
    
    /**
     * The Damage Reprots that belong to the Company.
     */
    public function damageReports()
    {
        return $this->hasMany('App\DamageReport');
    }
    
    
    DamageReport model:
    
    /**
     * The company of a damagereport
     *
     */
    public function company()
    {
        return $this->belongsTo('App\Company');
    }
    
    
    // In your controller
    public function index()
    {
        $damageReportId = 1;
        $company = Company::whereHas('damageReports', function ($q) use($damageReportId) {
            $q->where('id', $damageReportId);
        })->first();
    
        dd($company);
    }
    
    // Or 
    public function index()
    {
        $damageReportId = 1;
        $company = DamageReport::find($damageReportId)->company;
        dd($company);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

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