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

Laravel fetch data from two tables without join with pagination

我想从两个表 propertiesproperties_x 中获取结果,其中 properties.addressproperties_x.address_x 喜欢 test 和 laravel 分页。

这两个表之间没有外键关系。

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

使用union all合并两个table的数据,

并从数据库中的这些数据中获取列,因此您可以使用分页。

试试这样:

$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);

不知道有没有别的办法,不过我觉得很管用

$res= [];

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

array_push($res,$tableOne);


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

array_push($res,$tableTwo);

现在 $res 有两个数据 table 在一起

union all 然后 laravel 查询构建器为 mysql union 提供 unionAll 方法。当你在做大项目或 ERP 级项目时,大多数情况下你需要使用 union 从具有多个 table 的数据库中获取数据。在以下示例中,您可以看到如何在 Laravel 5.

中使用 union all

示例:

$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);