jeudi 22 juin 2017

Laravel: Querying and accessing child objects in nested relationship with where clauses Many to Many relationship

Hi I have a problem to make my laravel query

Model Regions

class Region extends Model
{
    protected $table = 'regions';

    protected $guarded = [

    ];

    public function county()
    {
        return $this->belongsTo('App\Models\County');
    }


    public function companies()
    {
        return $this->belongsToMany('App\Models\CompanyInfo', 
        'region_company','region_id','company_id');
    }

Model Category

class Category extends Model
{
    protected $table = 'categories';

    protected $guarded = [];


    public function companies()
    {
        return $this->belongsToMany('App\Models\Company', 'categories_company','category_id','company_id');
    }
}

Model Company

class Company extends Model
{

    protected $table ='companies';

    protected $guarded = [

    ];

    public function regions()
    {
        return $this->belongsToMany('App\Models\Region', 'region_company','company_id','region_id');
    }

}

I have a input form where I want to filter by category and region and the output should be categories with companies if possible but I want to show only 10 companies per category. Not sure it is is possible.

here is what I have till now

$categories = $request->input('categories');

    $region = $request->input('regions');

    $companies = Category::whereIn('id',$categories)->with([
        'companies.regions' => function ($query) use ($region) {
            $query->whereIn('id', $region);
        }])->get();

the problem here is that it is filtering the categories but it is still giving me all companies not filtering out the once that belong to certain region.

thank you Dany



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2rGoT6B
via IFTTT

Aucun commentaire:

Enregistrer un commentaire