2017-02-07 10 views
1

私は、典型的なアカウント - >郵便番号のシナリオで作業しています。 、アカウントと郵便番号アカウントに私がLaravel eager loading and LIKE filter

public function zipcode() { 
    return $this->belongsTo(Zipcode::class); 
} 

を追加index.blade.phpはこのようなものです:私は2 MODEL2を持って

<td>{{$account->id}}</td> 
    <td>{{$account->fullname}}</td> 
    <td>{{$account->address}}</td> 
    <td>{{$account->zipcode->fulllocation}}</td> 
... 

私は、リストの一番上にフィルタ(基本的な入力テキストを追加しますいかなる検索が全て挿入されていない場合は、試験及び作動のこの時点で

public function index(Request $request) 
{ 
    $search = $request->search; 
    //The instructions in the closure given to when() will only be applied if the first argument is evaluated to true 
    $accounts = Account::with('zipcode')//https://laravel.com/docs/4.2/eloquent#eager-loading 
        ->when($search,function ($query) use ($search) { 
        $query->where('fullname','like','%'.$search.'%'); 
        return $query; 
        }) 
        ->latest() 
        ->paginate(15); 
    return view('accounts.index', compact('accounts'))->with('search',$search); 
} 

シナリオ:)accounts.fullnameに含まれる文字列のように、コントローラは次のようですアカウントがリストされていれば、結果は正しくフィルタリングされます。

私の必要性は、accounts.fullname OR accounts.zipcode.fulllocationに挿入された文字列を検索することです。ヘルプのあらゆる種類に

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'fulllocation' in 'where clause' (SQL: select count(*) as aggregate from `accounts` where `fullname` like %foo% or `fulllocation` like %foo%) 

感謝を:私はこのエラーが発生し、それをしようとすると

$accounts = Account::with('zipcode')//https://laravel.com/docs/4.2/eloquent#eager-loading 
    ->when($search,function ($query) use ($search) { 
       $query->where('fullname','like','%'.$search.'%'); 

       $query->orWhere('fulllocation','like','%'.$search.'%');//ADDED THIS 

       return $query; 
      }) 
    ->latest() 
    ->paginate(15); 

:私はこのようにコントローラをmodifiyしてみてください。

答えて

3

実際にzipcodesテーブルにあるときに、クエリがfulllocationをアカウントテーブルで検索しているためです。このことができます

$query->where('fullname', 'like', '%' . $search . '%') 
    ->orWhereHas('zipcode', function ($q) use ($search) { 
     $q->where('fulllocation', 'like', '%' . $search . '%'); 
    }); 

https://laravel.com/docs/5.3/eloquent-relationships#querying-relationship-existence

希望:

にあなたのような何かを試みることができます!

+0

それは私が必要としているものと、私が探しているものです。実際には、** Oracle **テーブルに基づいてMySqlテーブルとZipcodeモデルに基づいてアカウントモデルを構成し始めます。クエリに** mysqlschema.zipcode **が見つからないため、ソリューションを適用するとエラーが発生します。現時点では、複雑である必要はありませんので、私はmysqlをすべて動かし、正しく動作します(Laravel側では何も変わりません)。私はこの事を今後の研究のためにとどめています。 – AlexMI

関連する問題