我需要定义一个全局筛选器,以便只获取表中所需的文件。问题是,在需要根据其他关系进行过滤时,我需要在查询中进行连接。我的问题是,在定义了全局作用域之后,关系包含了连接中涉及的所有表的所有行,这使得代码崩溃,因为有不明确的列。
如何过滤后才能返回products表?
我基于这篇文章中的代码
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;
});
}
}在model类中
protected static function boot() {
parent::boot();
static::addGlobalScope(new PublishedScope);
}发布于 2015-04-28 22:50:10
也许不是最好的解决方案,但是,使子查询在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);
}https://stackoverflow.com/questions/29913412
复制相似问题