The account you're visited is private.
The account you're visited is private.
The account you're visited is private.
The account you're visited is private.
The account you're visited is private.
The account you're visited is private.
The account you're visited is private.
The account you're visited is private.
The account you're visited is private.
The account you're visited is private.
The account you're visited is private.
The account you're visited is private.
The account you're visited is private.
The account you're visited is private.
The account you're visited is private.
The account you're visited is private.

Dalam contoh kali ini kita akan mencoba menampilkan artikel yang kebetulan mempunyai tipe yang berbeda, archived, scheduled, published. Nah jika kita ingin menampilkannya, sangat salah jika kita buat seperti ini.

$publishedPosts = Post::where('status','=','published')->get();
$archivedPosts = Post::where('status','=','archived')->get();
$scheduledPosts = Post::where('status','=','scheduled')->get();

Kenapa salah, karena sebenarnya apa yang dihasilkan dari query tersebut akan menghasilnya query yang berulang terhadap satu tabel seperti ini:

select * from posts where status = 'published'
select * from posts where status = 'archived'
select * from posts where status = 'scheduled'

Nah untuk solusinya, Anda bisa memakai fungsi whereIn dari eloquent seperti ini.

$posts =  Post::whereIn('status',['published', 'archived', 'scheduled'])->get();

$published_posts = $posts->where('status','=','published');
$archived_posts = $posts->where('status','=','archived');
$scheduled_posts = $posts->where('status','=','scheduled');

Dengan demikian, maka query yang terjadi dalam sql akan satu kali saja seperti ini:

select * from posts where status in ( 'published', 'archived', 'scheduled' )

Itu saja untuk artikel ini, semoga bermanfaat 🙂

2

Share on

Irsyad A. Panjaitan

Let's start living like no one can help us in any event, so that when we are helped in certain times, it becomes a plus in itself..