我正在工作台环境中开发一个包。我有一个这样的模型
<?php namespace Vendor\Webshop\Models;
use Vendor\Webshop\Models\Country as Country;
use Illuminate\Database\Eloquent\Model as Eloquent;
/**
* A catalog
*/
class Catalog extends Eloquent {
// Define the database
protected $table = 'catalogs';
// Mass assignment restriction
protected $guarded = array('id');
// Return the countries related to this catalog
public function countries() {
return $this->belongsToMany('Vendor\Webshop\Models\Country');
}
/**
* Returns whether to enforce the compability check or not
*/
public function getForceCompabilityTest() {
return $this->force_compability_check;
}
}
?>我想知道我是否可以拥有像这样的自定义实例getter
public function getDefaultCatalogs() {
return Catalog::where('is_default_catalog', '=', true)->get();
}}在类本身中。这是可能的吗?或者这些方法只可用于具体的实例,我可以从类的外部像Catalog::getDefaultCatalogs()一样调用它们吗?
发布于 2013-07-11 18:50:59
Laravel的雄辩能力支持这种行为--它被称为“查询作用域”http://laravel.com/docs/eloquent#query-scopes
在您的模型中,如下所示:
class Catalog extends Eloquent {
public function scopeDefault($query)
{
return $query->where('is_default_catalog', '=', true);
}
}然后,您可以使用此调用检索记录
$defaultCatalog = Catalog::default()->get();
// or even order them, if there are more than 1 default catalog. And so on...
$defaultCatalog = Catalog::default()->orderBy('created_at')->get();发布于 2013-07-11 16:57:22
我只是将该方法作为静态方法添加到了Eloquent模型中,它工作得很好。如果任何人对此有意见,请让我知道。
public static function getDefaultCatalog() {
return Catalog::where('is_default_catalog', '=', true)->firstOrFail();
}}https://stackoverflow.com/questions/17587738
复制相似问题