Question: **Below is the schema for tblagegroup**

```
CREATE TABLE `tblagegroup` (
  `AgeGroupID` tinyint(3) UNSIGNED NOT NULL,
  `MinAge` int(11) NOT NULL,
  `MaxAge` int(11) NOT NULL
);

```

**Below is the schema for tblcontentlibrary**

```
CREATE TABLE `tblcontentlibrary` (
  `ContentLibraryID` int(11) NOT NULL,
  `AgeGroupID` tinyint(3) UNSIGNED NOT NULL
);

```

AgeGroupID is associated in both tables.

I am trying to get those records from tblcontentlibrary where MinAge >= 2 and MaxAge is <= 4

Below is what i tried.

```
\App\Models\ContentLibraryModel
::with('AgeGroup')
->where('MinAge', '>=', $years)
->where('MaxAge', '<=', $years)
->get();

```

I am getting below error.

> 
> Column not found: 1054 Unknown column 'MinAge' in 'where clause' (SQL:
>  select \* from `tblcontentlibrary` where `MinAge` >= 0 and `MaxAge` <=
>  0)
> 
> 
> 

Am I missing anything?

Answer: 
If your relations are correct, [this should work](https://laravel.com/docs/5.1/eloquent-relationships#constraining-eager-loads):

```
\App\Models\ContentLibraryModel::with(['AgeGroup' => function ($query) use ($years) {
    $query->where('MinAge', '>=', $years)->where('MaxAge', '<=', $years);
}])->get();

```
My working query is below.

```
\App\Models\ContentLibraryModel
    ::selectRaw('CL.*, AG.MinAge, AG.MaxAge')
    ->from('tblcontentlibrary as CL')
    ->join('tblagegroup as AG', 'AG.AgeGroupID', '=', 'CL.AgeGroupID')
    ->where('AG.MinAge', '<=', $years)
    ->where('AG.MaxAge', '>=', $years)
    ->get();

```