user3844579
user3844579

Reputation: 505

Laravel 5.3 relationship returns wrong one

class Company extends Model
{
 public function company_settings()
{
    return $this->belongsToMany('CompanySetting');
}

}

class SettingsGroup extends Model
{
public $table = 'settings_groups';

public function comapanySettings() {

    return $this->hasMany('CompanySetting');
}
}

 class CompanySetting extends Model
{
public function groups () {

    return $this->belongsToMany('SettingsGroups');

}

public function company_settings()
{
    return $this->belongsToMany('Company');
}

}

I want to get the companys settings: Company::whereHas('company_settings', function ($q) use ($company) { $q->where('company_id',$company->id);})->get();

But it returns the company, not the settings. What am i doing wrong? Thanks!!

Edited with all the Models, $companies = Company::with('company_settings')->get(); also returns all the companies

Thanks!

Upvotes: 0

Views: 87

Answers (2)

You can't build relation with settings in this query. whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

Try this:

  Company::with('company_settings')
        ->whereHas('company_settings', function ($q) use ($company)
        {
              $q->where('company_id',$company->id);
        })->get();

Upvotes: 0

Eric Tucker
Eric Tucker

Reputation: 6335

Then to get the settings you can do:

$companies = Company::with('settings')->get();

Then access the first company's settings:

$companies ->first()->company_settings;

Since this returns a collection all of the collection methods are available to you:

https://laravel.com/docs/5.3/collections

To loop through them you could do:

$companies->each(function($company) {
    $company->company_settings;
    // Your logic here
});

Upvotes: 2

Related Questions