简体   繁体   中英

Laravel 5.1 hasMany relation query

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?

$farmers = App\Farmer::with(['crops' => function ($query) {
    $query->where('farming_crop_name', '=', 'wheat');
}])->get();

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..

Update after comment

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM