问题描述
*请注意,这是关于Laravel 4的问题,而不是关于Laravel 3(使用Fluent)的问题
*Note this is a question regarding Laravel 4, not Laravel 3 (which uses Fluent)
是否可以在Laravel 4中扩展DB类?
Is it possible to extend the DB class in Laravel 4?
我已经尝试过像这样简单的事情:
I've tried something as simple as this:
class Content extends DB {}
在我的路线上有此提示
print_r(Content::table('content')->get());
似乎可以使用"DB"之类的"Content".
And it seems to work as far as using "Content" like "DB".
但是,如果我尝试默认设置表名(类似于在Eloqeunt中设置表名)并使用诸如where或join之类的功能,则会出现如下错误:
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());
以此为错误:
实际上,我想做的是这样的事情.因此,我可以添加一个执行多个联接/联接的函数,但将其集成到使用DB的常规流程中.因此,该类将如下所示:
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');
}
}
它将被这样称呼:
Content::orderBy('time_added')
->take(10)
->joinPermissions($permission_mask)
->get();
这可能吗?我想这与需要扩展DB以外的其他类有关,因为当您使用DB :: table();时DB返回了其他内容.但是我真的很努力遵循Laravel中的代码并查找正在发生的事情,这似乎与照明有关,但老实说,我不确定这是什么.我还尝试查看Eloquent,以了解它是如何做到的,但是我再次发现Laravel很难环顾四周并了解正在发生的事情.
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.
推荐答案
尝试使用Eloquent和范围:
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();
这篇关于Laravel 4-是否可以扩展DB类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!