Laravel.如何查找具有特定最新相关模型的模型 [英] Laravel. How to find models which has specific latest related model
问题描述
Laravel 5.3.
Laravel 5.3.
包模型具有许多步骤模型.
步骤模型有一个名为status
的列,其类型为tiny int,而为created_at
列.
例如,包A
具有以下步骤:
A Package Model has many Step Models.
The Step Model has a column calls status
whose type is tiny int and created_at
column.
For example, a package A
, has these steps:
- 十月. 18 10:00,状态1
- 十月. 19 09:00,状态2
而且,程序包B
具有以下步骤:
And, a package B
, has these steps:
- 十月. 19 08:00,状态1
- 十月. 19 09:00,状态2
- 十月. 19 10:00,状态3
就像这样,很多软件包,每个软件包都有很多步骤.
Just like that, many packages, each of them has many steps.
A
的最新步骤的状态为2,而B
的最新状态为3
A
's latest step's status is 2 and B
's is 3
我的问题是,如何找到最新步骤状态为2的软件包?预期结果是软件包的集合,在此示例中,应包含A
.
My problem is, how to find Packages whose latest step status is 2? The expected result is a collection of packages, in this example, should contains A
.
我尝试将其添加到我的包装模型中.
I have tried add this in my Package Model.
public function steps()
{
return $this->hasMany('App\Step');
}
public function status()
{
return $this->steps()->latest()->limit(1);
}
并使用
Package::whereHas('status', function ($q) {
$q->where('status', 2);
})->get();
但无法获得预期的结果.
but can't get expected result.
没想到的是,如果Packages Table仅包含1行,则Package B
的预期结果是一个空集合.但它返回包含B
的集合.
What not expected is, if Packages Table has only 1 row, the Package B
, expected result is an empty collection. But it return a collection contains B
.
我也尝试过将Package Model中的状态功能更新为
I have also tried update the status function in Package Model to
public function status()
{
return $this->hasOne('App\Step')->latest();
}
但它仍然无法正常工作.
but it still not work.
那么,正确的方法是什么?谢谢你.
So, what is the right way? Huge thank to you.
推荐答案
这很有挑战性.我想不出一种解决方案,可以通过执行一个雄辩的查询来实现所需的功能.但是我发现了一种可以通过两个步骤为您提供结果的方法-即查询+过滤器.
This is quite challenging. I couldn't think of a solution that you can achieve what you want by doing a single Eloquent query. However I found a way that gives you the result in two steps - i.e. query + filter.
但是在此之前,您需要为Package
模型添加范围:
But before that you need to add a scope to your Package
model:
public function scopeOfStatus($query, $status)
{
return $query->whereHas('steps', function($q) use ($status)
{
$q->where('status', $status);
});
}
第1步:编写查询以检索至少与您的给定状态相匹配至少一步的所有软件包:
Step 1: Write a query that retrieves all packages with at least one step matching your given status:
$status = 1;
$packages = Package::with('steps')->ofStatus($status)->get();
第2步::过滤结果以仅获取最后一步与您的给定状态相匹配的软件包:
Step 2: Filter the result to get only packages which their last step matches your given status:
$packages = $packages->filter(function($package) use ($status)
{
return $package->steps->last()->status == $status;
});
最终结果是其最后一步具有status == 1
The final result is a collection of all packages that their last step has status == 1
这篇关于Laravel.如何查找具有特定最新相关模型的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!