Reputation: 11208
I've created a function that executes a raw query (for a search form). This returns the query-result like return \DB::Select(\DB::Raw("SELECT ..."))
The model which holds this method also contains relationship functions. Let's say this model has a relationship function products
and the results from the raw query are stored in $items.
When I try something like
@foreach($items as $item)
@foreach($item->products as $product)
{{ $product->someVar }}
@endforeach
@endforeach
I get a undefined property "Undefined property: stdClass::products" error. I assume this is because Laravel doesn't know yet that $items in fact is a collection of the Model-class that has the relationship with "products".
Is there a way to "bind" those relationship functions to a raw query?
Upvotes: 1
Views: 1866
Reputation: 11208
I found the solution kinda unknowingly where to look in de Model-class. There's a method hydrate
(and hydrateRaw
). The documentation tells us the following about it:
"Create a collection of models from plain arrays."
In case anyone is wondering, this is how to fix the problem above:
return self::hydrate(
\DB::Select(
\DB::Raw("SELECT * FROM `table`")
)
);
Upvotes: 4