Laravel,具有连接的全局范围

时间:2015-04-28 07:48:01

标签: php laravel

我需要定义一个全局过滤器,以便只获取表中的desires文件。问题是需要根据其他关系进行过滤,因为我需要在查询中进行连接。 我的问题是,在定义全局范围之后,关系具有连接中涉及的所有表的所有行,这会使代码崩溃,因为存在不明确的列。

我怎样才能在过滤后返回产品表?

我基于这篇文章中的代码

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);
  }

1 个答案:

答案 0 :(得分:0)

也许不是最好的解决方案,但是在sql中进行子查询可以正常工作。

public function apply(Builder $builder){


  $table = $builder->getModel()->getTable();

    $sql = '
        SELECT "products".* 
        FROM (
            SELECT  "products".* 
            FROM    "products" INNER JOIN "products_categories" AS 
                    "p_c" ON "p_c"."product_id" = "products"."id" INNER JOIN 
                    "categories" AS "cat" ON "p_c"."category_id" = "cat"."id" 
             WHERE  (
                    cat.id != 888130
                    )
        )AS products';  

    $builder
      ->select("products.*")
      ->from(DB::raw("($sql) AS products"));
  }
  $this->addWithDrafts($builder);
}