Reputation: 2896
I'm trying to develop a simple web-app where I store a farmer's detail and his/her cultivation information.
I have 2 database tables - farmer
and farmer_crop
.
farmer table
id | name | phone
farmer_crop table
id | farmer_id | farming_location | farming_crop_name | harvest_end_date
I made 2 controllers - FarmerController
& FarmerCropController
. A Farmer can cultivate many crops so the Farmer has hasMany
with FarmerCrop. Now I want to show a list of farmers using the FarmerController
's index method where I get farmers who are farming wheat. How do I go about achieving this?
Upvotes: 0
Views: 70
Reputation: 20944
You would use something like.
class = FarmerController extends Controller
public function index()
{
$results = FarmerCrop::with('farmers')
->where('farming_crop_name', 'wheat')
->get();
return view('farms.crops', compact('results'));
}
I don't know the name of your models so best guess above..
In that case you would just add an additional were clause.Ezequiel was alos correct with his answer. But I will modify his and add in your new requirements.
$farmers = App\Farmer::with(['crops' => function ($query) {
$query->where('farming_crop_name', 'wheat');
}])
->where('user_type_id', 3)
->get();
Upvotes: 0
Reputation: 2348
$farmers = App\Farmer::with(['crops' => function ($query) {
$query->where('farming_crop_name', '=', 'wheat');
}])->get();
Upvotes: 3