I think what you're looking for is with()
.
Before I get to that though, you actually have a bigger problem there than it seems. Matei Mihai actually touched on this.
When you have something like $Customer->Equipment
, you're actually making use of Eloquent's "dynamic properties". What this means is, there's a magic __get()
in there somewhere that says if the desired property doesn't exist on the target model, check to see if it has a relation method by that name. And if so, lazy-load it if it hasn't already been eager-loaded via with()
or load()
.
So when you do $Customer->Equipment
, it's basically a shortcut for $Customer->Equipment()->get()
.
Next thing to consider is that the result of get()
is an Eloquent\Collection, which is a child-class to Support\Collections. And Support\Collections have their own version of the where()
method.
All that to say, $Customer->Equipment->where('SNStatus', 'SHIPPED')
does not result in running a query that looks like:
SELECT * FROM Equipment WHERE customerID = ? AND SNStatus = 'SHIPPED'
What you're doing is running this instead:
SELECT * FROM Equipment WHERE customerID = ?
And then asking the Collection class to filter the resulting set by SNStatus='SHIPPED'
afterwards. This can be a huge performance hit and even max out your servers RAM depending on how big those tables are. I think what you're really looking for there is this:
$Customer->Equipment()->where('SNStatus', 'SHIPPED')->get()
By calling on the actual Equipment()
method rather than the dynamic property, you're telling Eloquent that you're not quite ready for it to execute the query yet, because you're still appending conditions to it.
(Also just as a side-note, your naming-convention hurts my OCD a little bit, methods should always be "camelCased". Only class names have their first letter capitalized.)
So... back to the question you actually asked, and including an understanding of the difference between Model::where()
and Collection::where()
, what we have is something like this:
$resutls = $Customer->Equipment()->with(['Part'])->where('SNStatus', 'SHIPPED')->get();
Since you wanted to specify a couple fields within the Parts table that you actually care about, you can use a constrained eager-load
$resutls = $Customer->Equipment()->with(['Part' => function (Illuminate\Database\Eloquent\Builder $query) {
$query->select([
'PartNum', //Per Equipment::Part(), This needs to be there for the relation to be mated with its parent
'ClassID',
'PartDescription'
]);
// Since PHP always handles objects by-reference, you don't actually need to return $query after having altered it here.
}])->where('SNStatus', 'SHIPPED')->get();
This will give you a nested Part
object with just the fields you care about on each Equipment
model element within the Eloquent\Collection
results.
As for how to handle these results within your blade file, I'll differ to Matei Mihai on that, I think that answer is pretty good.