I got this two tables (Estado(Status) and Proyecto(Proyect)), that have a pivot table in between called EstadoProyecto(statusProyect), I'm trying to access only the proyects that have either 2 or 3 in their id_status(id_estado) field, and that have the most recent date. It Works when using find(using either 2 or 3), but it gives me the error. " Eloquent: Property [proyectos] does not exist on this collection instance, Many to Many Relationship" when trying to send an array to the find method, or when using the get method. It gives me the same error when I'm not using the find method with only one value. Here are my models, and the query I'm trying to use. model1 model2 model3
This is the query that works right now: query Thanks in advance. Diego:)
Your query is returning a collection because there may be multiple entries for your model returned by the find
method that Eloquent provides so you could either use the first
method like this:
$estados = Estado::whereHas('proyectos', function ($query) {
$query->whereIn('id_estado', [2, 3])
->orderBy('fecha_estado', 'DESC');
})
->with('proyectos', function ($query) {
$query->whereIn('id_estado', [2, 3])
->orderBy('fecha_estado', 'DESC');
})
->first();
With the above snippet, to get multiple results that match those conditions you would only need to replace the first
method with get
The above code with give you can an instance of a single Estado
model.
Otherwise, if you are going to use something along the original approach you can use get
and return a collection, you can iterate over them in a foreach loop:
$estados = Estado::whereHas('proyectos', function ($query) {
$query->orderBy('fecha_estado', 'DESC');
})
->with('proyectos')
->get();
foreach ($estados as $estado) {
$estado->proyectos->id;
}
Or you could access the items in the collection like you would an array, granted you know that you definitely have the entry required in your results:
$estados[0]->proyectos->id;
If you are looking to get just one result, using Eloquent's first
method is often the best option for this.
I hope this helps!
Extra info:
The find
method in Eloquent can accept either a single value or an array of values as an argument and in the case of either no value being passed to it or an array of values being passed to it, a Collection may be returned rather than an instance of a single model.
The get
method on the other hand can be used without supplying any arguments and will return collection every time (although these can still hold no items if the underlying query did not yield any results)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.