使用数组值检索数据 - laravel

时间:2018-04-16 10:21:52

标签: php laravel

我的任务是显示所选组的所有联系人。当我选择两个像facebook and instagram这样的gorup时,我必须显示属于这两个组的所有联系人。

当我选择下面的多个组并执行return $explode_groups时,我会获得1,2这两个组的ID。

但我的问题是,当我以return $selected_contacts显示联系人时,我只收到第1组的联系人。

为什么会这样?

 public function customers()
    {
        return $this->belongsToMany('App\Customer','customer_group','group_id','customer_id')
        ->withTimestamps();
    }

客户

 public function groups()
    {
        return $this->belongsToMany('App\Group','customer_group','customer_id','group_id')
        ->withTimestamps();
    }

控制器

$get_selected_groups = $request->get('group');

$explode_groups = implode(', ', $get_selected_groups);

$selected_groups = Group::where('id',$explode_groups)->first();

$selected_contacts = $selected_groups->customers()->get();

响应

{"id":2,"title":"test","no_of_contacts":0,"user_id":1,"created_at":"2018-04-15 23:55:30","updated_at":"2018-04-15 23:55:30","customers":[{"id":1,"name":"Benson Jones Thomson","phone":"0247878234","group_id":null,"user_id":1,"created_at":"2018-04-16 00:14:20","updated_at":"2018-04-16 05:31:05","pivot":{"group_id":2,"customer_id":1,"created_at":"2018-04-16 05:33:08","updated_at":"2018-04-16 05:33:08"}},{"id":2,"name":"Lawrence Pitcher","phone":"0244371112","group_id":null,"user_id":1,"created_at":"2018-04-16 07:59:15","updated_at":"2018-04-16 07:59:15","pivot":{"group_id":2,"customer_id":2,"created_at":"2018-04-16 07:59:15","updated_at":"2018-04-16 07:59:15"}}]}

3 个答案:

答案 0 :(得分:2)

您应该使用whereIn()从给定数组中选择多个ID并加载每个模型使用with()方法的关系。

像:

$get_selected_groups = $request->get('group');

return Group::whereIn('id', $get_selected_groups)->with('customers')->get();

答案 1 :(得分:0)

试试这个

$selected_contacts = Customer::whereHas('groups', function($q) use ($explode_groups){
            $q->whereIn('id', $explode_groups);
})->get();

答案 2 :(得分:0)

你应该试试这个

$selected_groups = Group::whereIn('id',$get_selected_groups)->get();

$selected_contacts = array();

foreach($selected_groups as $selected_group){

   $selected_contacts[] = $selected_group->customers()->get();

}