0
votes
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!

2
That mean you've Many To Many relationship, show use more code please. at least the both Models.Zakaria Acharki

2 Answers

2
votes

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

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