0

后端列表:按 HasMany 关系中的字段排序和过滤

我有两个与戏剧作品及其表演相关的模特:

class Play extends Model
{
 ...
public $table = 'johar_theater_plays';
public $hasMany = ['playtimes' => 'johar\Theater\Models\PlayTime'];
}

class PlayTime extends Model
{
...
public $table = 'johar_theater_plays_times';
public $belongsTo = ['play' =>  ['johar\Theater\Models\Play']];
}

我将通过play表格中的关系管理器管理游戏时间。

为了playtimesplay-list 中显示,我发现了两种可能性:

playtimes:
    relation: playtimes
    select: time
    type: myRenderFunction

playtimes:        
    type: myRenderFunction
    sortable: true

第一种类型使用 in 集合调用我的函数$value,第二种使用 JSON 字符串调用。

在第二种类型中,我可以按播放时间排序——它可能只是对 JSON 字符串进行排序,但这没关系。

但是我发现没有办法创建一个过滤范围来过滤掉今天之后没有表现的所有戏剧。 我试过了

scope:
  condition: playtimes.time > now()

恕我直言,它的所有可能变化。以及创建一个范围函数,我在其中修改了不同的 where 子句。问题始终是 SQL 将 JOIN 放入 group_concat:

"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'time' in 'where clause' 
(SQL: select `johar_theater_plays`.*, 
    (select group_concat(time separator ', ') 
    from `johar_theater_plays_times` 
    where `johar_theater_plays_times`.`play_id` = `johar_theater_plays`.`id`)
    as `playtimes` 
from `johar_theater_plays` 
where `time` > 2016-12-12 00:00:00 
order by `playtimes` desc)" on line 662 of E:\..\Illuminate\Database\Connection.php

所以简短的问题是:PlayHasManyPlaytimes

4

1 回答 1

0

我找到了解决方案。如果有人有一个更漂亮的,我会很高兴,但现在我将使用这个范围函数:

public function scopeFutureonly($query)
{
    $table = 'johar_theater_plays_times';
    if(!$this->is_scoped) {
        $query->join($table, 'johar_theater_plays.id', '=', $table . '.play_id');
        $query->groupBy($table . '.play_id');
        $query->where($table . '.time', '>', date("Y-m-d H:i:s"));
    }
    $this->is_scoped = true;
}

isScoped是模型中的受保护变量,用于防止在多次调用范围时多次添加查询。(在这里感谢planetadeleste)。

唯一的问题是,我在 SQL 中有两个 JOINS:一个在 concat 中,一个在常规中。我认为这只能通过完全手动创建 SQL 来规避,这将破坏 october 的目的......

于 2017-01-23T16:34:14.337 回答