首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Laravel模型获取类的实例

Laravel模型获取类的实例
EN

Stack Overflow用户
提问于 2013-07-11 15:44:15
回答 2查看 6.6K关注 0票数 3

我正在工作台环境中开发一个包。我有一个这样的模型

代码语言:javascript
运行
复制
<?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

代码语言:javascript
运行
复制
public function getDefaultCatalogs() {
  return Catalog::where('is_default_catalog', '=', true)->get();
}}

在类本身中。这是可能的吗?或者这些方法只可用于具体的实例,我可以从类的外部像Catalog::getDefaultCatalogs()一样调用它们吗?

EN

Stack Overflow用户

回答已采纳

发布于 2013-07-11 18:50:59

Laravel的雄辩能力支持这种行为--它被称为“查询作用域”http://laravel.com/docs/eloquent#query-scopes

在您的模型中,如下所示:

代码语言:javascript
运行
复制
class Catalog extends Eloquent {

    public function scopeDefault($query)
    {
        return $query->where('is_default_catalog', '=', true);
    }

}

然后,您可以使用此调用检索记录

代码语言:javascript
运行
复制
$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();
票数 3
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17587738

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档