user3844579 user3844579 - 27 days ago 20
PHP Question

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!

Answer

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