【问题标题】:Laravel 5.2 subquery - filter rows by polymorphic pivot table last rowLaravel 5.2 子查询 - 按多态数据透视表最后一行过滤行
【发布时间】:2016-12-28 18:47:20
【问题描述】:

我已经被困在这个问题上几天了,想知道是否有人可以提供帮助。

数据库表: “页面”、“状态”、“状态分配”

页面模型:

protected $appends = ['status'];

public function statuses()
{
    return $this->morphToMany('App\Models\Status', 'statusable', 'status_assignments')->withPivot('id', 'assigned_by_user_id', 'locked')->withTimestamps();
}

public function getStatusAttribute()
{
    return $this->statuses()->orderBy('pivot_id', 'DESC')->first();
}

public function scopeWithStatus($query, $statuses)
{
    $query->with('statuses');

    if(is_array($statuses) && count($statuses) > 0)
    {
        $query->whereHas('statuses', function($q) use($statuses)
        {
            $cs = $q->orderBy('pivot_id', 'DESC')->first();
            foreach($statuses as $status) $q->where('id', $status)->where('pivot_id', $cs->pivot->id);
        });
    }

    return $query;
}

状态模型:

public function pages()
{
    return $this->morphedByMany('App\Models\Page', 'categorizable', 'category_assignments')->withTimestamps();
}

我要做的是检索一个页面列表,其中分配的最新状态的 id 为 ['array_of_status_ids'](scopeWithStatus 中的'$statuses')

$pages = Page::withStatus([1,2,3,4])->get();

我们将不胜感激地收到任何关于此的想法!在此先感谢克里斯。

【问题讨论】:

    标签: laravel eloquent polymorphism relationships


    【解决方案1】:

    首先,pages() 关系看起来使用了错误的数据透视表详细信息。

    '可分类','category_assignments'

    应该是'statusable', 'status_assignments'

    有时我发现在混合中加入一些原始 SQL 比编写复杂的查询生成器语句更简单。

    使用子查询检查每个页面的最新状态条目包含在 $statuses:

    public function scopeWithStatuses($query, $statuses = [])
    {
        $subQuery = '(select status_id from status_assignments'
            . ' where status_assignments.statusable_id = pages.id'
            . ' and status_assignments.statusable_type = "App\\\Test\\\Page"'
            . ' order by status_assignments.id desc limit 1)';
    
        $query->whereIn(\DB::raw($subQuery), (array) $statuses);
    }
    

    【讨论】:

    • 你是个传奇我的朋友
    猜你喜欢
    • 2017-02-28
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 2015-06-24
    相关资源
    最近更新 更多