2016-11-10 3 views
0

複数のクエリやハッカーを使わずにモデルインスタンスに追加の属性を読み込むことは可能ですか?私に説明してみましょう:既存の雄弁なモデルインスタンスに多くの属性をロードする

// I got a tiny model with only id loaded 
$model = Model::first(['id']); 
// Then some code runs 
// Then I decide I'd need `name` and `status` attributes 
$model->loadMoreAttributes(['name', 'status']); 
// And now I can joyously use name and status without additional queries 
$model->name; 
$model->status; 

は雄弁に私の架空のloadMoreAttributes機能に似たものがありますか?

私は初心者ではなく、Model::find($model->id)などをよく知っています。彼らはあまりにも口語的です。

お気軽にお問い合わせください。

答えて

1

あなたはそうのように、このloadMoreAttributes方法を有することが雄弁モデルを拡張することができる:

use Illuminate\Database\Eloquent\Model; 

class YourModel extends Model 
{ 
    public function loadMoreAttributes(array $columns) 
    { 
     // LIMITATION: can only load other attributes if id field is set. 
     if (is_null($this->id)) { 
      return $this; 
     } 

     $newAttributes = self::where('id', $this->id)->first($columns); 

     if (! is_null($newAttributes)) { 
      $this->forceFill($newAttributes->toArray()); 
     } 

     return $this; 
    } 
} 

あなたのモデルでこれを行うことができますこの方法:

しかし

$model = YourModel::first(['id']); 
$model->loadMoreAttributes(['name', 'status']); 

制限をこのハックには限界があります。モデルインスタンスの一意のidが既に取得されている場合にのみ、loadMoreAttributes()メソッドを呼び出すことができます。

このヘルプが必要です。