簡體   English   中英

如何在laravel中的單個查詢中從多個表中選擇多個列?

[英]How to select multiple columns from many tables in a single query in laravel?

我正在編寫函數以從許多表中搜索多個列,例如用戶表和產品表,這是我正在嘗試的方法

Route::post ( '/search', function () {
$q = Input::get ( 'q' );
$user = DB::table('users')->where ( 'name', 'LIKE', '%' . $q . '%' )->orWhere ( 'email', 'LIKE', '%' . $q . '%' )->get ();
if (count ( $user ) > 0)
    return view ( 'welcome' )->withDetails ( $user )->withQuery ( $q );
else
    return view ( 'welcome' )->withMessage ( 'No Details found. Try to search again !' );

這僅用於選擇許多列,但只有一個表是用戶表,但是我還有另一個表是產品表,並且有product_name列。 所以我想將其包括在搜索查詢中。 我應該使用哪種方法,聚合方法或聯合方法? 我嘗試了一些可能的方法,但還沒有運氣。 請指導我。謝謝。

這是東西 (由於您擁有ID為1的用戶和ID為1的產品,因此我假設了一些觀點)

1)聯合方法:

$users= \App\User::FindOrFail(1);
$productsWithUsers = \App\Products::where(['id'=>1])->union($table1)->get();

現在$ productsWithUsers具有用戶和產品的所有列

暫無
暫無

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

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