I have table training_schedules
and years
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?
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.
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.
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.
One To One (Polymorphic) One To Many (Polymorphic) Many To Many (Polymorphic)
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With