:私は再利用可能な方法には、この特定の部分をしたいのですが Laravel 5.2
User::whereNotIn('id', $ids)
->select(['id', 'email'])
->with([
'profile' => function ($query) {
$query->addSelect(['id', 'user_id', 'first_name', 'last_name']);
},
])->get();
User::whereNotIn('id', $ids)
->select(['id', 'email'])
->withSimpleProfile() // use default columns
->get();
および/または
User::whereNotIn('id', $ids)
->select(['id', 'email'])
->withSimpleProfile(['id', 'user_id', 'first_name', 'last_name'])
->get();
withSimpleProfile
はコンタます:連鎖するための
public function withSimpleProfile($columns)
{
$this->with([
'profile' => function ($query) use ($columns) {
$query->addSelect(['id', 'user_id', 'first_name', 'last_name']);
}]);
return $this;
}
これを行う方法はありますか?
UPDATE
ありビルダー方法macroように見えるんが、それは使用されるかもしれない場所/方法を見つけ出すことはできません。
ALTERNATIVE(あっけなく解決)私はUserRepositoryを作る再利用可能な方法のための一般的
、それは呼び出すためのオリジナルのコード例が含まれているだろうが、私は簡単にするために、クエリにカスタムチェーンのメソッドを追加したいです再利用し、それほど緊密に結合してはいけません。最も可能性の高い方法は、私自身のIlluminate/Eloquent/Builder.php
を作成してメソッドを追加し、何とかこのビルダーを代わりに使用することですか?しかし、Laravelはいつもより簡単に拡張できるようにこれらの素晴らしい方法を持っています。
これが今の仕事に表示され、UserRepositoryのDIを使用し続けますが、何らかの理由で、それは非常に洗練された感じがしない:
User::whereNotIn('id', $ids)
->select(['id', 'email'])
->with($this->users->simpleProfile())
->get();
UserRepository :: simpleProfileが返されます。
public function simpleProfile() {
return [
'profile' => function ($query) {
$query->addSelect(['id', 'user_id', 'first_name', 'last_name']);
},
];
}
を
確かにそうです。特にダイナミックスコープも含まれています。乾杯! – mtpultz