【问题标题】:Laravel model getting instances of the classLaravel 模型获取类的实例
【发布时间】:2013-07-09 09:24:32
【问题描述】:

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

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

}

?>

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

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

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

【问题讨论】:

  • 你尝试过类似Vendor\Webshop\Models\Catalog::getDefaultCatalogs()
  • 这不是关于命名空间,更多的是关于方法的静态调用,“从类外部”有点误导,sry

标签: model laravel laravel-4


【解决方案1】:

Laravel 的 Eloquent 支持这种行为 - 它被称为“查询范围”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();

【讨论】:

    【解决方案2】:

    我刚刚将该方法作为静态方法添加到 Eloquent 模型中,它工作正常。如果有人对此有 cmet,请告诉我。

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

    【讨论】:

    • 看我的回答。您的解决方案也很好,但是使用此代码,您无法在“getDefaultCatalog”之后链接另一个方法调用。
    猜你喜欢
    • 1970-01-01
    • 2011-10-28
    • 2012-03-29
    • 2014-07-14
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    相关资源
    最近更新 更多