1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| // Laravel 5.8.12未満の場合
use Illuminate\Database\Eloquent\Builder;
// 方法1: サブクエリを使用
$postIds = Post::where('published', true)->pluck('id');
$videoIds = Video::where('is_public', true)->pluck('id');
$comments = Comment::where(function ($query) use ($postIds, $videoIds) {
$query->where(function ($q) use ($postIds) {
$q->where('commentable_type', Post::class)
->whereIn('commentable_id', $postIds);
})->orWhere(function ($q) use ($videoIds) {
$q->where('commentable_type', Video::class)
->whereIn('commentable_id', $videoIds);
});
})->get();
// 方法2: マクロを定義
Builder::macro('whereMorphedTo', function ($relation, $model) {
return $this->where($relation . '_type', get_class($model))
->where($relation . '_id', $model->getKey());
});
|