如何构建添加连接子句的通用范围?

时间:2014-05-25 05:12:13

标签: php laravel

我试图写一个"范围"这会在我的查询中添加左连接。

使用示例:

$bookings = Booking::where('bookings.company_id','=',Auth::user()->company_id)
    ->withGuid();

我已经开始工作,但我已经对类名和表名进行了硬编码:

GuidScope.php

<?php

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\JoinClause;

class GuidScope implements \Illuminate\Database\Eloquent\ScopeInterface {

    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  Builder $builder
     * @return void
     */
    public function apply(Builder $builder) {
        $builder->macro('withGuid', function (Builder $builder) {
            $builder->leftJoin('guids', function (JoinClause $join) {
                $join->on('guids.pk', '=', 'bookings.id');
                $join->on('guids.type', '=', DB::raw("'Booking'"));
            });

            return $builder;
        });
    }

    /**
     * Remove the scope from the given Eloquent query builder.
     *
     * @param  Builder $builder
     * @return void
     */
    public function remove(Builder $builder) {
        // TODO: Implement remove() method.
    }
}

GuidTrait.php

<?php

trait GuidTrait {
    public static function bootGuidTrait() {
        static::addGlobalScope(new GuidScope);
    }
}

如何删除GuidScope.php中的硬编码booking.idDB::raw("'Booking'")?有没有办法从BuilderJoinClause对象获取表名和模型类名?

1 个答案:

答案 0 :(得分:0)

我更多地挖掘了源代码。你可以做到这一点!

public function apply(Builder $builder) {
    $builder->macro('withGuid', function (Builder $builder) {
        $model = $builder->getModel();
        $builder->leftJoin('guids', function (JoinClause $join) use ($model) {
            $join->on('guids.pk', '=', $model->getTable().'.'.$model->getKeyName());
            $join->on('guids.type', '=', Sql::raw('?',[get_class($model)]));
        });

        return $builder;
    });
}