覆盖Eloquent Query Builder

时间:2014-12-04 15:49:49

标签: php laravel laravel-4 eloquent query-builder

我正在尝试覆盖Eloquent的查询生成器。

我为MyModel尝试了以下内容:

<?php

class CustomQueryBuilder extends Illuminate\Database\Query\Builder
{
    public function get($columns = array('*'))
    {
        die('get');
    }
}

use CustomQueryBuilder as Builder;
class MyModel extends \Illuminate\Database\Eloquent\Model
{
    // the model that needs the custom query builder
}

但是当我运行MyModel::get()时,它仍会返回对象而不是死亡。

任何想法如何使这项工作?

2 个答案:

答案 0 :(得分:1)

我不确定您要做什么,但至少,您需要在模型中实施(并覆盖)Illuminate\Database\Eloquent\Model::newBaseQueryBuilder才能使用它你的新Builder类。

/**
 * Get a new query builder instance for the connection.
 *
 * @return \Illuminate\Database\Query\Builder
 */
protected function newBaseQueryBuilder()
{
    $conn = $this->getConnection();
    $grammar = $conn->getQueryGrammar();
    return new CustomQueryBuilder($conn, $grammar, $conn->getPostProcessor());
}

答案 1 :(得分:0)

我认为最好的方法是:

<?php

namespace MyNamespace\Models;
use Illuminate\Database\Eloquent\Builder as BaseBuilder;
use \Illuminate\Database\Eloquent\Model;


class Builder extends BaseBuilder
{
   public function like($key, $value){
       return $this->orWhere($key, 'like', '%' . $value . '%');
   }
}  


class MyModel extends Model
{

    protected $table = 'mytable';

    public function newEloquentBuilder($query)
    {
       return new Builder($query);
    }
}