简体   繁体   English

如何在laravel中的单个查询中从多个表中选择多个列?

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

I am writing function to search multiple columns from many tables like users table and product tables,here is how i am trying 我正在编写函数以从许多表中搜索多个列,例如用户表和产品表,这是我正在尝试的方法

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 !' );

this is only for selecting many columns but only one table which is users table, but i have another table which is product tables and product_name column is there. 这仅用于选择许多列,但只有一个表是用户表,但是我还有另一个表是产品表,并且有product_name列。 So i want to include it in search query. 所以我想将其包括在搜索查询中。 which method should i use, aggregate method or union method? 我应该使用哪种方法,聚合方法或联合方法? i tried some possible methods, but no luck yet. 我尝试了一些可能的方法,但还没有运气。 Please guide me.Thanks. 请指导我。谢谢。

Here is something. 这是东西 (i have assumed some points as you have user with id 1 and product with id 1) (由于您拥有ID为1的用户和ID为1的产品,因此我假设了一些观点)

1) Union Method: 1)联合方法:

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

Now $productsWithUsers have all the columns from User and Product 现在$ productsWithUsers具有用户和产品的所有列

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM