Home  >  Article  >  Backend Development  >  How to query the latest associated model of a model with specific conditions in Laravel?

How to query the latest associated model of a model with specific conditions in Laravel?

WBOY
WBOYOriginal
2016-10-20 10:08:541146browse

I just asked a question on StackOverflow, please answer it.

http://stackoverflow.com/ques...

A Package model has many Step models. There are two fields in Step, the tinyint type status field and the timestamp field.
Suppose a Package A has the following steps

  • At 10 o'clock on the 18th, status is 1

  • At 9:00 on the 19th, status is 2

Suppose a Package B has the following steps

  • At 8:00 on the 19th, status is 1

  • At 9:00 on the 19th, status is 2

  • At 10 o'clock on the 19th, status is 3

In this way, the latest step status of A is 2, and the latest step status of B is 3.

Then, how to query the packages whose latest step status is 2?

I tried adding

to the package model
<code>public function steps()
{
    return $this->hasMany('App\Step');
}

public function status()
{
    return $this->steps()->latest()->limit(1);
}
</code>

Then query like this

<code>Package::whereHas('status', function ($q) {
    $q->where('status', 2);
})->get();
</code>

But I can’t get the expected results.

The so-called not expected result means that if there is only B in the packages table, I want to query the packages whose latest step status is 2, and the latest step status of B is 3, so the result should be empty, but the result of querying like this is not It is not empty, but contains B.

Then I tried to change to

<code>public function status()
{
    return $this->hasOne('App\Step')->latest();
}
</code>

It’s still the same.

I just learned Laravel, and I was very confused when I encountered this problem. I also searched a lot of Google, but I couldn’t find the answer I wanted. I hope you can help me, thank you!

Using Laravel 5.3

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn