简体   繁体   中英

How Can I Use Global Scope in Laravel Query Builder? (No Eloquent Model)

I'm working with too many mysql large views. I don't want to use Eloquent Model for the views.

I created "ViewBalance extends Illuminate\\Support\\Facades\\DB". Everything worked as I wanted.

But i need to set init() method for company scope.

How can I use the global scope without init() method?

ViewModel

<?php

namespace App\Models\Views;

use App\Facades\CoreService;
use Illuminate\Support\Facades\DB;

class ViewBalance extends DB
{
     const COMPANY_COLUMN = 'company_id';
     const TABLE = 'view_balances';

     public static function init()
     {
         return parent::table(self::COMPANY_COLUMN)
             ->where(self::COMPANY_COLUMN, CoreService::companyId());
     }
}

In Controller

<?php

$data = ViewBalance::init()->get(); // Worked!

I have answered my own question. Because, I don't want to edit my question for more complicate. I want to talk about a solution to this problem.

I added $table_view variable and getView() method in Laravel model. If you want, you can create trait for clean codes.

It can be accessed easily views. Also it is part of the main model.

For example;

Laravel Basic Account Model

class Account extends Model {

    protected $table = 'accounts';

    protected $table_view = 'view_accounts';

    public function getView()
    {
        return \DB::table($this->table_view)->where('global_scope', 1);
    }

}

Laravel Account Controller

class AccountController extends Controller {

    public function index()
    {
        $items = (new Account)->getView()->paginate(20);
    }

}

public function scopeActive($query)
{
    return $query->where('active', true);
}

or

public function scopeInactive($query)
{
    return $query->where('active', false);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM