简体   繁体   中英

Laravel Eloquent query model with relationship

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);

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);
}

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM