dtg7662 2017-11-25 09:27
浏览 157
已采纳

检索项目基于Laravel中的多个IDS

I have a relationship between employees and items. It's a one-to-many relationship (i.e employee can have many items).

For instance, there are two employees Mark and Bill.

Mark bought items with item_no 1-0234, 1-0235 respectively.

Bill bought items with item_no 1-0236, 1-0237 respectively.

Item numbers are unique and therefore can be used to find the customer who is in possession.

This is my code to find customers items belong to. I select ids of all items using a checkbox.

What I am looking to achieve is, I want to find all employees based on the item selected, retrieve the phone numbers and item_nos using explode and process a message to them.

Controller

<?php

public function processMessage(Request $request)
{
    $ids = $request->ids; // i am able to get the item_nos selected, eg. 1 - 0234, 1 - 0236

        $split = explode(",", $ids);
        if (request()->ajax()) {
            $employees = Employee::whereHas('items', function ($emp) use ($split) {
                $emp->where('id', $split);
            })->get();

            $get_name = [];
            $get_phone = [];

            foreach ($emps as $key => $emps) {
                $get_name[] = $emps->name;
                $get_phone [] = $emps->phone;
            }

        }

     return ['success' => $get_phone];
}

PS: in the code, imagine i have selected two items with item_nos 1-0234, 1-0236. That is, my code should return two phone numbers, i.e for Mark and Bill but it returns just one of them, which is Mark's. Why is this happening

  • 写回答

1条回答 默认 最新

  • duanreng3439 2017-11-25 10:32
    关注

    If i correct, following should help inside your query function-

    $emp->whereIn('id',$split);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?