2017-11-12 5 views
0

Laravel Eloquentを使用してコードを最適化するソリューションを探しています。クエリービルド/コード最適化でのEloquent Attributes/Modified Relation Dateの追加

私の問題は、属性を条件付きで追加したいということです。この属性は、基本的に変換された多対多の関係です。

<?php 

namespace App\Http\Controller; 

/** 
* Class Category 
*/ 
class Category extends Controller 
{ 

    /** 
    * @return Collection 
    */ 
    public function index() 
    { 
     return Category::withCount('countries')->get(); 
    } 

    /** 
    * @param int $id 
    * 
    * @return Category 
    */ 
    public function show($id) 
    { 
     $result = Category::where('id', $id) 
      ->with('countries') 
      ->firstOrFail(); 

     $result->countries_list = ''; 

     return $result; 
    } 
} 

マイカテゴリーのモデルは次のようになります(簡体字):私のコントローラで私はこれを持っている時点では

(簡体字)

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

/** 
* Class Category 
*/ 
class Category extends Model 
{ 

    /** 
    * The accessors to append to the model's array form. 
    * 
    * @var array 
    */ 
    protected $appends = [ 

    ]; 

    /** 
    * The attributes that should be hidden for arrays. 
    * 
    * @var array 
    */ 
    protected $hidden = [ 
     'countries', 
    ]; 

    /** 
    * @return string 
    */ 
    public function getCountriesCountAttribute() 
    { 
     return trans_choice('labels.countries', $this->original['countries_count']); 
    } 

    /** 
    * @return 
    */ 
    public function getCountriesListAttribute() 
    { 
     return $this->countries->pluck('alpha_2'); 
    } 

    /** 
    * Get the related Countries. 
    */ 
    public function countries() 
    { 
     return $this->belongsToMany(
      Country::class, 
      'category_country', 
      'category_id', 
      'country_id' 
     ); 
    } 
} 

国のモデルは、国のリストだけですid、name、Alpha2コードなどが含まれています。リストが常に含まれるため、countries_listを追加するために保護された$を使用することはできません。 これは、他のいくつかのオカレンスで使用されているため、私の国モデルも変更できません。

私は何を探していますがこれにコントローラーのコードを最適化する方法です:

<?php 

namespace App\Http\Controller; 

/** 
* @return Collection 
*/ 
public function index() 
{ 
    return Category::withCount('countries')->get(); 
} 

/** 
* @param int $id 
* 
* @return Category 
*/ 
public function show($id) 
{ 
    return Category::where('id', $id) 
     ->withAttribute('countries_list') // An array of all country aplha 2 codes 
     ->firstOrFail(); 
} 
+0

は、私はこの例では、助けになると思いますhttps://stackoverflow.com/questions/44070497/laravel-eloquent-return-only-one-value/44071133#44071133 –

+0

ありませんこれは私がwhanものではありません。質問をお読みください! – Webdesigner

+0

あなたが探しているものを遅延読み込み関連のモデルではありませんか? –

答えて

-1

あなたが照会した後countries_list属性にアクセスすることができます(それをクエリでを含みません) 。

public function show($id) 
{ 
    $category = Category::findOrFail($id); 

    $list = $category->countries_list; // this calls getCountriesListAttribute() 
} 
関連する問題