简体   繁体   中英

How to Use WhereIn Query in Laravel 8

Controller

    public function detail(Peserta $peserta)
    {
        // get konfirmasi_id
        $konfirmasi = KonfirmasiPembayaran::where('email',$peserta->email)->select('id')->get();

        $payments   = BankSettlement::whereIn('konfirmasi_id',array($konfirmasi->id))->get();
        // dd($payments);
        $tagihan    = Tagihan::where([['peserta_id', $peserta->id],['type', 3]])->first();
        return view('data.peserta.detail', ['data' => $peserta, 'payments' => $payments,'tagihan' => $tagihan]);
    }

I want to display data from BankSettlement based on konfirmasi_id. Here I try to use WhereIn Query like this, but still error "Property [id] does not exist on this collection instance.".

确认变量

$konfirmasi has data like the image above.

What is the correct way to display data from BankSettlement based on konfirmasi_id ? Thankyou

Try this changes:

    $konfirmasi = KonfirmasiPembayaran::where('email',$peserta->email)->pluck('id')->toArray();

    $payments   = BankSettlement::whereIn('konfirmasi_id',$konfirmasi)->get();

This is the wrong way to change a collection to array. $payments=BankSettlement::whereIn('konfirmasi_id',array($konfirmasi->id))->get();

You should do this

public function detail(Peserta $peserta)
    {
        // get konfirmasi_id
        $konfirmasi = KonfirmasiPembayaran::where('email',$peserta->email)
                         ->select('id')
                         ->get()
                         ->pluck('id')
                         ->toArray(); //This will return an array of ids

        $payments   = BankSettlement::whereIn('konfirmasi_id',$konfirmasi)->get();
        // dd($payments);
        $tagihan    = Tagihan::where([['peserta_id', $peserta->id],['type', 3]])->first();
        return view('data.peserta.detail', ['data' => $peserta, 'payments' => $payments,'tagihan' => $tagihan]);
    }

Edit: Read Laravel Collections|Pluck

If you do not have to reuse the result of $konfirmasi then it would be better to use subquery. Writing a subquery is optimized way. if you write two different query then there will be two seperate database connection request.

Laravel subquery

$konfirmasi = KonfirmasiPembayaran::where('email',$peserta->email)->select('id');

$payments   = BankSettlement::whereIn('konfirmasi_id', $konfirmasi )->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM