Laravel雄辩的过滤结果

时间:2019-04-18 18:13:32

标签: laravel eloquent

在我的控制器中,我从消息模型中检索消息列表。我正在尝试添加一个过滤器,但是这些过滤器互相抵消了。

// Controller
public function __construct(Message $messages)
{
    $this->messages = $messages;
}

public function index($filter = null)
{
    $messages = $this->messages
        ->actioned($filter == 'actioned' ? false : true)
        ->ignored($filter == 'ignored' ? true : false)
        ->get();

    return view('...
}

// Model
public function scopeActioned($query, $actioned = true)
{
    $constraint = ($actioned ? 'whereNotNull' : 'whereNull');

    return $query->$constraint('ts_actioned');
}

public function scopeIgnored($query, $ignored = true)
{
    return $query->where('is_ignored', ($ignored ? 'Yes' : 'No'));
}

如何设置Eloquent,以便仅在$ filter设置为“ actioned”时才调用scopeActioned,而忽略则相同?

1 个答案:

答案 0 :(得分:1)

简单方法:

public function index($filter = null)
{
    $query = $this->messages->query();
    //applying filter
    if($filter == 'actioned') {
        $query->actioned();
    }
    if($filter == 'ignored') {
        $query->ignored();
    }

    $messages = $query->get();

    return view('...
}

作用域功能中的另一种方法。

// Model
public function scopeActioned($query, $actioned = true)
{
    if($actioned) {
        $query->whereNotNull('ts_actioned');
    }

    return $query;
}

public function scopeIgnored($query, $ignored = true)
{
    if($ignored) {
        $query->where('is_ignored', 'Yes');
    }

    return $query;
}