laravelで、リレーション先のカラムも参照したOR検索を実装したいです
現在
```ここに言語を入力
$table1
$table->increments('id');
$table->string('name');
$table->string('prefecture');
$table->string('city');
$table->text('address');
$table->integer('table2_id');
$table->timestamps();
```ここに言語を入力 $table2 $table->increments('id'); $table->string('name'); $table->string('password'); $table->timestamps();
という二つのモデルを作成しています。table1はtable2にbelongToの関係にあります。
コントローラーで
public function index(Request $request){ $search_word = $request->search_word; $q = Table1::Where('name','like','%'.$search_word.'%') ->orWhere('prefecture','like','%'.$search_word.'%') ->orWhere('city','like','%'.$search_word.'%') ->orWhere('address','like','%'.$search_word.'%') ->get(); }
と言った内容のコードを書いています。
一つの言葉で、複数のカラムを検索にかけ、データを取得するのが目的です。
ここから、table2のnameカラムにも同時にorWhere検索をかけたいと思うのですが、方法がどうしてもわかりません。どなたがアドバイスいただけると幸いです。
試したこと
join文でテーブルを結合
→結果 table1->nameが表示されるところにTable2->nameが表示されるなど、viewで上手く表示されなかった
またtable2のpasswordなどの外に出してはいけない情報までviewに送信されるため、password流出の恐れがあるのではないかと感じた。
whereHas()の使用
->whereHas('table2', function($query)use($search_word) { $query->orWhere('name','like','%'.$search_word.'%'); })->get();
→結果 上手く取得できなかった
参考
https://www.webopixel.net/php/1412.html
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。