Laravel 模型获取类的实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17587738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:07:23  来源:igfitidea点击:

Laravel model getting instances of the class

modellaravellaravel-4

提问by pfried

I am developing a package in the workbench environment. I have a model like

我正在工作台环境中开发一个包。我有一个像

<?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;
    }

}

?>

I wondered if i can have custom instance getters like

我想知道我是否可以拥有像这样的自定义实例 getter

public function getDefaultCatalogs() {
  return Catalog::where('is_default_catalog', '=', true)->get();
}}

within the class itself. Is this possible or are the methods only available to a concrete instance, can i call them like Catalog::getDefaultCatalogs()from outside of the class?

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

采纳答案by Andreyco

Laravel's Eloquent support this kind of behaviour - it's call "Query Scopes" http://laravel.com/docs/eloquent#query-scopes

Laravel 的 Eloquent 支持这种行为 - 它被称为“查询范围” http://laravel.com/docs/eloquent#query-scopes

In your model, to this:

在您的模型中,对此:

class Catalog extends Eloquent {

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

}

Then, you can retrieve record with this call

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

$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();

回答by pfried

I just added the method as a static method to the Eloquent model and it works fine. If anybody has comments on this, let me know.

我刚刚将该方法作为静态方法添加到 Eloquent 模型中,并且运行良好。如果有人对此有意见,请告诉我。

public static function getDefaultCatalog() {
  return Catalog::where('is_default_catalog', '=', true)->firstOrFail();
}}