簡體   English   中英

如何從Laravel 5中的相關表中獲取數據?

[英]How to get data from related tables in laravel 5?

我的頁面上有一個搜索表單,可以搜索多個表格,該如何執行以下操作並正確搜索? 我希望能夠搜索代理商名稱,客戶名稱和類型名稱以及用戶名和密碼:

我的看法如下

@foreach ($accounts as $account)
                <tr>
                    <td> {{$account->client->name}} </td>
                    <td> {{$account->agency->name}} </td>
                    <td> {{$account->type->name}} </td>
                    <td> {{$account->username}} </td>
                    <td> {{$account->password}} </td>
                    <td><a href="{{route('accounts.edit',$account->id)}}"><span class="fa fa-edit"></span></a></td>
                </tr>
                @endforeach

正確搜索用戶名和密碼,但聯接未帶來任何結果

    public function index(){

    $search = \Request::get('search');

    $accounts =
        Account::where('clients.name','like','%'.$search.'%')
        ->orWhere('agencies.name','like','%'.$search.'%')
        ->orWhere('types.name','like','%'.$search.'%')
        ->orWhere('username','like','%'.$search.'%')
        ->orWhere('password','like','%'.$search.'%')
        ->Join('types', 'accounts.id', '=', 'accounts.type_id')
        ->Join('agencies', 'accounts.id', '=', 'accounts.agency_id')
        ->Join('clients', 'accounts.id', '=', 'accounts.client_id')
        ->paginate(20);

      return view('accounts',compact('accounts'));
    }

更新::這有效:

       ->Join('types', 'accounts.type_id', '=', 'types.id')
       ->Join('agencies', 'accounts.agency_id', '=', 'agencies.id')
       ->Join('clients', 'accounts.client_id', '=', 'clients.id')

您的加入似乎有誤

->Join('types', 'accounts.id', '=', 'accounts.type_id')
->Join('agencies', 'accounts.id', '=', 'accounts.agency_id')
->Join('clients', 'accounts.id', '=', 'accounts.client_id')

查看使用帳戶表在'='的兩側如何需要一側具有類型/代理機構/客戶才能加入工作。

所以這就像

->Join('types', 'accounts.id', '=', 'types.type_id')
->Join('agencies', 'accounts.id', '=', 'agencies.agency_id')
->Join('clients', 'accounts.id', '=', 'clients.client_id')

說那將需要您的數據庫結構來指出為什么不能從聯接查詢搜索中得到結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM