LoginSignup
1
1

More than 5 years have passed since last update.

Laravel5.3でEloquentObjectをCollectionにまとめる方法

Posted at

需要あるのかしら・・・

と思いながら備忘録的に書いています。

ことの発端は

  1. DBからとってきたEloquentオブジェクト
  2. KVSにmessagepackされたEloquentオブジェクト

この2つをマージしてCollectionにして呼び出し元では気にせずに

echo $model->name;

としたいというではありませんか!

結論

  • はてさてそんなことできるのかと思いLaravelのコードを読んでみて試してみた。
$fromdb = HogeModel::where('id', '>=', 100)->get();
$fromkvs = Cache::get('key_99');

// 単純に全くゼロの状態でつくりたいときは
$collection = \Illuminate\Database\Eloquent\Collection::make($fromkvs);

// マージしたいときは
$collection = $collection->merge($fromdb);
  • これで受け取った側はそのままforeachしてプロパティにアクセスができる。
  • わかってしまえば簡単ですね。
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1