Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple where conditions on eloquent model with optional where on relationship

I have table training_schedules

  • id (int, pk)
  • course_reference (varchar)
  • start_date (date)
  • end_date (date)
  • year_id (int, fk)

and years

  • id (int, pk)
  • value (int)

Now I want to create a search query using the TrainingSchedule eloquent model. I want to search by course_reference (using like) and start_date(optional) based on month (dropdownlist on form) and year (optional)

optional conditions means I will check if the form data for the fields are filled on the search form. If not I will just skip those conditions.

How can I achieve this using Eloquent ORM? if not, how to do it on another way?

like image 404
Jaime Sangcap Avatar asked Mar 17 '14 05:03

Jaime Sangcap


People also ask

What is polymorphic relationship in Laravel?

A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.

What is BelongsTo in Laravel?

BelongsTo is a inverse of HasOne. We can define the inverse of a hasOne relationship using the belongsTo method. Take simple example with User and Phone models. I'm giving hasOne relation from User to Phone. class User extends Model { /** * Get the phone record associated with the user.

How do you define many relationships in Laravel?

As we have defined the hasMany relationship on Brand model which return the related records of Product model, we can define the inverse relationship on the Product model. Open your app/Product. php model file and add a new method called brand() in it which will return the related brand of a product.

How many types of relationships are there in Laravel?

One To One (Polymorphic) One To Many (Polymorphic) Many To Many (Polymorphic)


1 Answers

You can create a query over multiple calls. So something like the following will probably do what you're looking for:

// start query off with a non-optional query
$results = TrainingSchedule::whereLike('course_reference', Input::get('course_reference'));

// only if we were sent a start date, add it to the query
if (Input::has('start_date')) {
    $results->whereStartDate(Input::get('start_date'));
}

// if we were sent a month, ensure start date's month is the same month as the one passed in
if (Input::has('month')) {
    $results->where(DB::raw('MONTH(`start_date`)'), Input::get('month'));
}

// only if we were sent a year, add it to the query
if (Input::has('year')) {
    $results->whereHas('year', function ($query) { $query->whereValue(Input::get('year')); });
}

 // get actual results from db
$results = $results->get();
like image 56
alexrussell Avatar answered Sep 28 '22 03:09

alexrussell