简体   繁体   English

Laravel 从两个表中获取数据而不用分页连接

[英]Laravel fetch data from two tables without join with pagination

I want to fetch results from two tables properties and properties_x where properties.address or properties_x.address_x like test with laravel pagination.我想从两个表propertiesproperties_x中获取结果,其中properties.addressproperties_x.address_x就像使用 laravel 分页test一样。

There is no foreign key relationship between these two tables.这两张表之间没有外键关系。

properties

id  name    address
1   test1   
2   test2   
3   test3   
4   test3   test
5   test4   test

properties_x

id  name    address
1   test1_x test
2   test2_x 
3   test3_x 
4   test3_x test
5   test4_x 

    Expected results:
    name     address
    test3    test
    test4    test
    test1_x  test
    test3_x  test

Use union all to union two table's datas,使用union all来联合两个表的数据,

And get the columns from these datas in DB, so you can use pagination.并从数据库中的这些数据中获取列,以便您可以使用分页。

try it like this:像这样尝试:

$p1 = DB::table('properties')
        ->where('address', 'test')
        ->select('name', 'address');

$p2 = DB::table('properties_x')
         ->where('address', 'test')
         ->select('name', 'address');

$p = $p1->unionAll($p2);

DB::table(DB::raw("({$p->toSql()}) AS p"))
->mergeBindings($p)
->select('name', 'address')
->paginate(10);

I don't know if there is another way, but it works for me well我不知道是否有其他方法,但它对我很有效

$res= [];

$tableONe = Property::where('address','test')->get();

array_push($res,$tableOne);


$tableTwo = PropertyX::where('address','test')->get();

array_push($res,$tableTwo);

now $res have both data table together现在 $res 将两个数据表放在一起

union all then laravel query builder provide unionAll method for mysql union. union all 然后laravel 查询构建器为mysql union 提供unionAll 方法。 when you are doing big project or ERP level project then mostly you require to use union for getting data from database with multiple table.当你在做大项目或 ERP 级别的项目时,大多数情况下你需要使用 union 从具有多个表的数据库中获取数据。 In Following example you can see how to use union all in Laravel 5.在以下示例中,您可以看到如何在 Laravel 5 中使用 union all。

Example:例子:

$silver = DB::table("product_silver")
    ->select("product_silver.name"
      ,"product_silver.price"
      ,"product_silver.quantity");
$gold = DB::table("product_gold")
    ->select("product_gold.name"
      ,"product_gold.price"
      ,"product_gold.quantity")
    ->unionAll($silver)
    ->get();
print_r($gold);
$users = User::select('id','name')
        ->where('name','LIKE','%'.$key.'%'); 
$properties = Property::select('id','name')
             ->where('name','LIKE','%'.$key.'%'); 
$results = Program::select('id','name')
          ->where('name','LIKE','%'.$key.'%') ->union($users)
          ->union($properties)
          ->simplePaginate();

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

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