Laravel Eloquent - How Do You Add a Where Condition to a Distantly Related Model Using the ORM? - laravel

I currently have the following:
Cars::with('cases')->with(['parts', 'parts.engines', 'parts.engines.metals'])
->orderBy('car_name', 'DESC')->orderBy('id', 'DESC');
The above will list all rows in my cars table along with the metal associated with the engine in each of those cars. The metals table is related to the cars table through the parts and then the engines tables.
I've tried using:
Cars::with('cases')->whereHas(['parts', 'parts.engines', 'parts.engines.metals'], function($query){
$query->where('weight', '=', 45)
})->orderBy('car_name', 'DESC')->orderBy('id', 'DESC');
But this errors out since whereHas() does not accept an array for its first parameter and I don't see a way to link to distant relationships with it.
How do I apply a WHERE conditional on a column in the metals table using the built-in ORM?

whereHas() only needs the name of the relationship for which you'd like to add the conditions. So, if you're trying to add the condition to the metals, you just need to restrict the parts.engines.metals relationship.
On a side note, when you eager load nested relationships, you don't need to also specify to load the intermediate relationship. That is, when you eager load parts.engines, you don't need to also eager load parts.
So, your query would look something like:
Cars::with(['cases', 'parts.engines.metals'])
->whereHas('parts.engines.metals', function($query) {
$query->where('weight', '=', 45)
})
->orderBy('car_name', 'DESC')
->orderBy('id', 'DESC');
This query will only retrieve cars that have a related metal with a weight of 45. Additionally, for those cars that are retrieved, it will also eager load all of the cases, parts, engines, and metals related to those cars.

I think you mean this:
Cars::with(['cases', 'parts', 'parts.engines', 'parts.engines.metals' => function($query){
$query->where('weight', '=', 45);
}])->orderBy('car_name', 'DESC')->orderBy('id', 'DESC');

Related

How to use AND in laravel database query

$konten = Konten::all()->where('kategori','Announcement' AND 'kategori','Activities')->sortByDesc('id');
It's not work what is the right query for using AND Logic in query sir ? im so sorry i don't have much knowledge to find out the way.. the point is i want $konten contains the row from Konten where the kategori is Announcement and Activities.. how to make it happen ? it just showing konten where the kategori is activities the announcement not passed..
You can chain several where to achieve AND:
$konten = Konten::where('kategori', 'Announcement')
->where('kategori', 'Activities')
->orderBy('id', 'desc')
->get();
Or use whereIn like this:
$konten = Konten::whereIn('kategori', ['Announcement', 'Activities'])
->orderBy('id', 'desc')
->get();
To achieve an AND in Laravel, you simply chain ->where() calls:
$konten = Konten::where('kategori','Announcement')->where('kategori','Activities') ...
As a side note, Konten::all() returns a Collection, and is no longer database logic. You shouldn't call ::all() unless you specifically need every record in the database.
Refactor to the following:
$konten = Konten::where('kategori','Announcement')
->where('kategori','Activities')
->orderBy('id', 'desc')
->get();
This will leverage the database to perform the filtering/ordering, instead of offloading every record into a Collection and allowing PHP to perform the same logic, which can be incredibly inefficient depending on the number of records.
try this:
$konten = Konten::whereIn('kategori', ['Announcement', 'Activities'])->orderBy('id', 'desc')->get();
I have a strong feeling that you probably seek for 'orWhere' clause... If you want ALL records when kategori column equals 'Announcement' and all records when kategori equals 'Activities' you sholud use orWhere clause like so:
$konten = Konten::where('kategori', 'Announcement')
->orWhere('kategori', 'Activities')
->orderBy('id', 'desc')
->get();
Or as mentioned in answers below you can use whereIn statement.

Accessing parent properties inside relationship query

An example:
$passing_students = App\Exam::whereHas('students', function ($query) {
$query->where('mark', '>=', $exam->pass_mark);
})->get();
I am interested in fetching all exams with students who passed however in the relationship query function I'm not sure how to access the parent model's properties such that I can complete the comparison. What should be in place of $exam->pass_mark?
Note that I'm looking for a solution that is done within the single query builder as I'm aware that this can be easily done in a separate foreach loop.
Probably instead of:
$query->where('mark', '>=', $exam->pass_mark);
you should use here:
$query->whereColumn('mark', '>=', 'exams.pass_mark');
Above exams.pass_mark is name of Exam model table (I assumed you use exams and column name from this table.

Lean Eloquent Results ->with() Eager Loading

I have a query I am working on that feeds into a javascript engine where there is a lot of information returned that isn't used in the javascript. The results are over 1MB and some of that is because of some eager loading. Here is the query:
$customers = Customer::where('customers.office_id', $officeid)
->where("customers.parent_id", null)
->with('lastAppointment')
->with('nextAppointment')
->select("customers.id","customers.family_id", "customers.gender", "customers.family_size", "family_value")
->get();
The relationship of lastAppointment creates a returned nested object with all the columns from the appointments table, where I really only want a single column of start_at
If I do a ->leftJoin() I can limit my results using the final select like this:
->leftJoin(DB::raw("(select customer_id, MAX(start_at) as lastAppointment from appointments group by customer_id) as appt"), 'customers.id', '=', 'appt.customer_id')
->select("customers.id","customers.family_id", "customers.gender", "customers.family_size", "family_value", "appt.lastAppointment")
I am just wondering if there is a way of doing something similar using ->with()?
You can use this code
->with('lastAppointment:_relation_id,start_at')
where _relation_id is customer_id or primary key of lastAppointment correspond model: depends on your table relation. See docs part of Nested Eager Loading
https://laravel.com/docs/5.5/eloquent-relationships#eager-loading p
The with function will accept a callback as the array value of the relationship key. You then have access to the underlaying query builder instance, I think this is what you want:
->with(['lastAppointment' => function($query) {
return $query->latest()->select('customer_id', 'start_at')
->groupBy('customer_id');
}])

Eloquent query if value in relationship isn't same as value in other relationship

I have four models: Item, Car, ItemLocation and Branch.
An Item has a Car and a ItemLocation via a person_id and a item_location_id field in the DB.
A Car has a branch_id which links to Branch, and an ItemLocation also has a branch_id in the same way.
What I want to do is to select all Items where their Cars's branch is not equal to their ItemLocation's branch.
I tried this statement, though I knew that it wouldn't work:
Item::with('car','item_location')
->where('car.branch_id', '<>', 'item_location.branch_id')
->get();
I'm aware of querying on relationships, but don't understand how to do that across relationships like this.
Any ideas?
Querying relationships won't help you, since you want to compare values from separate tables. You need joins:
$items = Item::select('items.*')
->join('item_locations as il', 'il.id', '=', 'items.item_location_id')
->join('cars', function ($j) {
$j->on('cars.person_id', '=', 'items.id')
->on('cars.branch_id', '<>', 'il.branch_id');
})
->get()
This will fetch all the items having both cars and item_location and matching your criteria. If you want to include also ones that don't have either of the relations, then use leftJoins instead and whereNull('cars.id')
ps. It's hard to read your question. Instead of describing these relationships, better simply show the tables with relevant fields.

Laravel3 Eloquent: Query for attribute in Many-To-Many Relation

This Problem blows my mind at the moment:
I have the following relation:
Groups --> Intermediate Many-To-Many Table <-- Cities (Every Group can have multiple Cities assigned)
Now I want to get all the Group-Models where the assigned City is either id X and id Y.
Like Saying "get me all the groups which are assigned to Boston and New York"
Is that possible with Laravel 3's Eloquent?
Thank you very much!
Matthias
In my experience, where clauses do not work inside of many-to-many relationships. But they do work if you eager load them.
Group::with(array('cities' => function($q) {
$q->or_where('id', '=', X);
$q->or_where('id', '=', Y);
})->get();
Extending aowie1's answer above (which is correct), it's often useful to nest or_where clauses (as this makes logical sense, especially if you're looking to expand the query with non-or-where conditions):
Group::with(array('cities' => function($q) {
$q->where(function($where) {
$where->or_where('id', '=', 'x');
$where->or_where('id', '=', 'y');
});
})->get();
Again, just expanding aowie1's answer, which I've upvoted, as it's correct - this is just some additional info regarding nested queries with or conditions :)

Resources