dongzhonggua4229
2019-07-03 13:42
浏览 106
已采纳

如何从数据库中获取另一个表中的数据?

I want to get data from table role_users , column role_id . For the moment, I have this in my controller :

$data['contact_users'] = DB::table('contacts')
                    ->join('users' , 'users.id', '=', 'contacts.contact_id')
                    ->join('industries' , 'industries.id', '=', 'users.industry_id')
                    ->join('countries' , 'countries.id', '=', 'users.country_id')
                    ->join('organization_types' , 'organization_types.id', '=', 'users.organization_type_id')
                    ->select('users.*','industries.industry','countries.country','organization_types.organization_type')
                    ->where('contacts.contact_id','!=',$id)
                    ->where('users.deleted_at','=',NULL)
                    ->whereIn('contacts.user_id', $contact_id)
                    ->whereNotIn('contacts.contact_id', $contact_id)
                    ->whereNotIn('contacts.contact_id', $inviter_id)
                    ->groupBy('contact_id')
                    ->take(4)
                    ->get();

I'm using it in view with this code :

{{$contact->industry_id}} or {{$contact->country_id}}

I need to use something like this.

{{$contact->role_id}}

which is working for every user.But I need to get data from role_users,column role_id.I don't know how to use ->join() and I need it so much.Thank you.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanao4503 2019-07-03 13:44
    已采纳

    I added one extra join and one select field at the end,

    $data['contact_users'] = DB::table('contacts')
        ->join('users', 'users.id', '=', 'contacts.contact_id')
        ->join('industries', 'industries.id', '=', 'users.industry_id')
        ->join('countries', 'countries.id', '=', 'users.country_id')
        ->join('organization_types', 'organization_types.id', '=', 'users.organization_type_id')
        ->join("role_users", "role_users.user_id","=","users.id")
        ->select('users.*', 'industries.industry', 'countries.country', 'organization_types.organization_type', "role_users.role_id")
        ->where('contacts.contact_id', '!=', $id)
        ->where('users.deleted_at', '=', null)
        ->whereIn('contacts.user_id', $contact_id)
        ->whereNotIn('contacts.contact_id', $contact_id)
        ->whereNotIn('contacts.contact_id', $inviter_id)
        ->groupBy('contact_id')
        ->take(4)
        ->get();
    
    打赏 评论

相关推荐 更多相似问题