2

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 Answers 3

3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You should use:

$company = DamageReport::find($damageReportId)->company;

Explanation:

DamageReport is the thing you know about, so the find($id) method will bring back the single model that you have the $id for.

Because DamageReport has its relationship to Company set up correctly, the ->company relationship will bring back the associated company model.

Comments

0

Just use belongsTo and hasMany method if the relationship is one-to-many.

https://laravel.com/docs/5.5/eloquent-relationships#one-to-many

So, your DamageReport model is right, and in your Company model,

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

Then in you controller, @Skrrp's answer is right,

$company = DamageReport::find($damageReportId)->company;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.