我有一个Article
,它由Post
、News
等扩展。当我在这些子类上调用 Eloquent 方法(例如 all()
)时,我希望它们按__CLASS__
过滤结果。类名的复数、低大小写版本将存储在文章表中某个枚举字段中type
。在打电话给Post::all()
的那一刻,我得到了一切,包括新闻文章。
是否有特定于 Laravel 的解决方案,我不必覆盖整个 Eloquent 功能?
文章
<?php
namespace App;
use Illuminate'Database'Eloquent'Model as Eloquent;
abstract class Article extends Eloquent{
protected $table = 'articles';
// TODO filter eloquent results by article type ( classname )
}
新闻
<?php
namespace App'Article;
class News extends 'App'Article{
}
我正在使用 Laravel 5,这是来自 master 分支的最新开发版本。
发现Laravel有一个内置函数newQuery
来覆盖QueryBuilder功能。这让事情变得容易多了。
<?php
namespace App;
use Illuminate'Database'Eloquent'Model as Eloquent;
abstract class Article extends Eloquent{
protected $table = 'articles';
public function __construct($attributes = array()){
parent::__construct($attributes);
$this->setAttribute('class_name',get_class($this));
}
public function newQuery($excludeDeleted = true){
$builder = parent::newQuery($excludeDeleted);
if ('Article' !== get_class($this)) {
$c = get_class($this);
$c = explode('''', $c);
$c = end($c);
$builder->where('type',"=", $c);
}
return $builder;
}
}
由于命名空间表示法,我需要爆炸。