Laravel 4 - Is it possible to extend the DB class?

烈酒焚心 提交于 2019-12-13 03:44:07

问题


*Note this is a question regarding Laravel 4, not Laravel 3 (which uses Fluent)

Is it possible to extend the DB class in Laravel 4?

I've tried something as simple as this:

class Content extends DB {}

With this in my route:

print_r(Content::table('content')->get());

And it seems to work as far as using "Content" like "DB".

But if I try and set the table name by default similar to how you would in Eloqeunt and use functions such as where or join I get an error like so:

print_r(Content::where('id', '!=', 4)->get());

With this as the error:

call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Database\MySqlConnection' does not have a method 'where'

Effectively what i'd like to do is something like this. Whereby I can add a function which does a number of joins/where's but integrate it into the normal flow of using DB. So the class would look like this:

class Content extends DB {
    public $table = 'content';

    public static function joinPermissions($permission_mask)
    {
        return self::where('permissions.mask', '=', $permission_mask)
            ->where('permissions.read', '=', 1)
            ->join('permissions', 'id', '=', 'content.permission_set');
    }
}

And it would be called like so:

Content::orderBy('time_added')
    ->take(10)
    ->joinPermissions($permission_mask)
    ->get();

Is this possible? I imagine it's something to do with needing to extend a different class other than DB because DB returns something else when you use DB::table();. But i'm really struggling to follow the code in Laravel and find what's going on, it seems to be something to do with illuminate but to be honest i'm not really sure what that is. I've also tried looking at Eloquent to see how that does it, but again I simply find Laravel so difficult to look around and understand what's going on.


回答1:


Try using Eloquent and scopes:

class Content extends Eloquent {
    public $table = 'content';

    public function scopeJoinPermissions($query, $permission_mask)
    {
        return $query->where('permissions.mask', '=', $permission_mask)
            ->where('permissions.read', '=', 1)
            ->join('permissions', 'id', '=', 'content.permission_set');
    }
}

Content::orderBy('time_added')
    ->take(10)
    ->joinPermissions($permission_mask)
    ->get();


来源:https://stackoverflow.com/questions/16753029/laravel-4-is-it-possible-to-extend-the-db-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!