【发布时间】:2015-07-06 22:46:49
【问题描述】:
我需要定义一个全局过滤器,以便仅获取表中的需求文件。问题是需要根据其他关系进行过滤,因为我需要在查询中进行连接。 我的问题是,在定义了全局范围之后,关系中包含了连接中涉及的所有表的所有行,这会使代码崩溃,因为列不明确。
过滤后我如何只能返回产品表?
我基于这篇文章中的代码
http://softonsofa.com/laravel-how-to-define-and-use-eloquent-global-scopes/
laravel 帮助 http://laravel.com/docs/4.2/eloquent#global-scopes
还有这个 Global filtering - how to use global scope in Laravel Eloquent
我的代码
class PublishedScope implements ScopeInterface {
public function apply(Builder $builder)
{
$table = $builder->getModel()->getTable();
$temp = $builder
->select("products.*")
->join('products_categories as p_c', 'p_c.product_id', '=', 'products.id')
->join('categories as cat', 'p_c.category_id', '=', 'cat.id')
->Where(function($query){
$query->where('cat.id', '!=', '888130');
}
);
$this->addWithDrafts($builder);
}
public function remove(Builder $builder)
{
$query = $builder->getQuery();
$column = 'cat.slug';
$bindingKey = 0;
foreach ((array) $query->wheres as $key => $where)
{
if ($this->isPublishedConstraint($where, $column))
{
unset($query->wheres[$key]);
$query->wheres = array_values($query->wheres);
$this->removeBinding($query, $bindingKey);
}
// Check if where is either NULL or NOT NULL type,
// if that's the case, don't increment the key
// since there is no binding for these types
if ( ! in_array($where['type'], ['Null', 'NotNull'])) $bindingKey++;
}
}
protected function removeBinding(Builder $query, $key){
$bindings = $query->getRawBindings()['where'];
unset($bindings[$key]);
$query->setBindings($bindings);
}
protected function addWithDrafts(Builder $builder){
$builder->macro('withDrafts', function(Builder $builder)
{
$this->remove($builder);
return $builder;
});
}
}
在模型类中
protected static function boot() {
parent::boot();
static::addGlobalScope(new PublishedScope);
}
【问题讨论】: