2013-07-11 3 views
2

워크 벤치 환경에서 패키지를 개발 중입니다. 난 내가 클래스 자체 내에서클래스의 인스턴스를 가져 오는 Laravel 모델

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

같은 사용자 정의 인스턴스 게터를 가질 수 있다면

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

} 

?> 

같은 모델은 내가 궁금합니다. 이게 가능합니까 아니면 구체적인 인스턴스에서만 사용할 수있는 메서드입니까? 클래스 외부에서 Catalog::getDefaultCatalogs()과 같은 식으로 호출 할 수 있습니까?

+0

'Vendor \ Webshop \ Models \ Catal와 같은 제품을 사용해 보셨습니까? og :: getDefaultCatalogs()' –

+0

그것은 클래스의 바깥 쪽에서 메서드의 정적 호출에 대한 네임 스페이스에 대해 많은 것이 아니 었습니다. 오해의 소지가 있었고, 슬프다. – pfried

답변

3

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(); 
+0

이것은 알아두면 유용하며 나에게 유용 할 수 있습니다. – pfried

0

방금 ​​Eloquent 모델에 정적 메서드로 메서드를 추가했는데 제대로 작동합니다. 누구든지 이에 대한 의견이 있으면 알려주십시오.

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

내 대답보기. 귀하의 솔루션은 괜찮지 만,이 코드를 사용하면 'getDefaultCatalog'다음에 다른 메소드 호출을 연결할 수 없습니다. – Andreyco

관련 문제