Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/232.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel雄辩多态范围最新第一项_Php_Laravel_Eloquent_Scopes_Has Many Polymorphs - Fatal编程技术网

Php Laravel雄辩多态范围最新第一项

Php Laravel雄辩多态范围最新第一项,php,laravel,eloquent,scopes,has-many-polymorphs,Php,Laravel,Eloquent,Scopes,Has Many Polymorphs,你好 在这里,我有点纠结于使用Laravel范围和雄辩的多态一对多关系获取最新项目 鉴于: 我使用的是Laravel6.x的最新版本 我有两种型号:网站和状态 Status模型是可重用的,可以与其他模型一起使用 每个网站都有多种状态 每次更改状态时,都会在数据库中创建一条新记录 活动网站状态是数据库中的最新状态 网站模式: class Website extends Model { public function statuses() { return $th

你好

在这里,我有点纠结于使用Laravel范围和雄辩的多态一对多关系获取最新项目

鉴于:

  • 我使用的是Laravel6.x的最新版本
  • 我有两种型号:
    网站
    状态
  • Status
    模型是可重用的,可以与其他模型一起使用
  • 每个网站都有多种状态
  • 每次更改状态时,都会在数据库中创建一条新记录
  • 活动网站状态是数据库中的最新状态
网站模式:

class Website extends Model
{
    public function statuses()
    {
        return $this->morphMany(Statuses::class, 'stateable');
    }

    public function scopePending($query)
    {
        return $query->whereHas('statuses', function ($query) {
            $query->getByStatusCode('pending');
        });
    }
}
状态模型:

class Statuses extends Model
{
    public function stateable()
    {
        return $this->morphTo();
    }

    public function scopeGetByStatusCode($query, $statusCode)
    {
        return $query->where('status_code', $statusCode)->latest()->limit(1);
    }
}

问题是当我打电话时:

Website::pending()->get();
pending()
作用域将返回所有分配了
pending
状态的网站,而不是当前处于活动状态的
pending
网站(如最新状态)。

以下是随
DB::getQueryLog()返回的查询

使用具有多态一对多关系的范围来获取待处理的网站的正确方法是什么

这里描述了类似的问题:


谢谢。

好的,在做了一些研究之后,我偶然发现了这篇文章:

结果证明这个解决方案很有说服力(很抱歉用了一个糟糕的双关语):


原始查询不太正确,它应该是
websites.id
而不是
website.id
。很好,但这只是一个打字错误,因为我在那里更改了一些措辞。SQL纯粹是一个示例输出。
select * from `websites` 
    where exists 
    (
        select * from `statuses` 
        where `websites`.`id` = `statuses`.`stateable_id` 
        and `statuses`.`stateable_type` = "App\\Models\\Website" 
        and `status_code` = 'pending' 
        order by `created_at` desc limit 1
    ) 
and `websites`.`deleted_at` is null
protected function scopePending($query)
{
    return $query->whereHas('statuses', function ($query) {
        $query->where('id', function ($sub) {
            $sub->from('statuses')
                ->selectRaw('max(id)')
                ->whereColumn('statuses.stateable_id', 'websites.id');
         })->where('status_code', 'pending');
    });
}