doujia9204 2019-02-18 17:21
浏览 89

在范围内设置后重写列

I wrote a scope which restricts all queries on a model. Those results should contain only data, which can be seen by the logged in user. To restrict such a query I join to a user table and limit the results by id IN (?,?,?,?,?,?,?,?). Further in that scope I use select([BASETABLE . '.*']) because I don't want the data of the partner join. Until here everything works fine. If I use that model and change the columns to what I need in that case, the columns keeps the definition from my scope. I can't overwrite them later.

Anyone has a solution or an idea?

I already looked into the classes (MysqlProcessor, MysqlConnection, Model, Eloquent\Builder, Query\Builder, ...) of laravel but can't find a solution.

// in scope called method to restrict
public function restrictByIds (Builder $query, Model $model)
{
    $ids = $this->getIdsByUser(); // [1,2,3,4,5,6]
    if (!empty($ids)) {
        $userModel = $model->user()->getModel();
        $userTable = $userModel->getTable();

        $query
            ->getQuery()
            ->select([$model->getTable() . '.*'])
            ->join(
                $userTable,
                $userTable . '.id',
                '=',
                $model->getTable() . '.user_id'
            )
            ->whereIn($userTable . '.id', $ids);
    }
}




// tries to overwrite columns
$model->getQuery()->select(['DATE(created) as time', 'count(*) AS count']);
$model->getQuery()->columns = ['DATE(created) as time', 'count(*) AS 
count'];
$model->getQuery()->addSelect(['DATE(created) as time', 'count(*) AS 
count']);
$model->getQuery()->addBinding(['DATE(created) as time', 'count(*) AS 
count'], 'select');
$model->getQuery()->bindings = ['select' => ['DATE(created) as time',
'count(*) AS count']];
$model->select(\DB::raw('DATE(created) as time, count(*) AS count'));
$model->columns = ['DATE(created) as time', 'count(*) AS count'];
$model->addSelect(\DB::raw('DATE(created) as time, count(*) AS count'));
$model->addBinding(['DATE(created) as time', 'count(*) AS count'], 
'select');
$model->bindings = ['select' => ['DATE(created) as time', 'count(*) AS 
count']];
  • 写回答

1条回答 默认 最新

  • douti0467 2019-02-19 09:32
    关注

    I found a solution. $model = Model::query() returns the Eloquent\Builder with active scope. To define the columns I use $model->getQuery()->select(). For any other functions (where, whereIn, orderBy, groupBy, ...) $model itself can be used. This way i get my custom columns with automated restriction.

    And use $model->getQuery()->addSelect in scopes instead of $model->getQuery()->select.

    评论

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图