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

lb3vh1jj  于 2023-01-18  发布在  其他
关注(0)|答案(4)|浏览(102)

我想从两个表propertiesproperties_x中获取结果,其中properties.addressproperties_x.address_x类似于带有laravel分页的test
这两个表之间没有外键关系。

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
qxgroojn

qxgroojn1#

使用union all合并两个表的数据,
并从DB中的这些数据中获取列,这样就可以使用分页了。
你可以这样试试看:

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

0aydgbwb2#

我不知道有没有别的办法,但对我很有效

$res= [];

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

array_push($res,$tableOne);

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

array_push($res,$tableTwo);

现在,$res同时拥有两个数据表

sf6xfgos

sf6xfgos3#

union all然后laravel查询生成器为mysql union提供unionAll方法。当你在做大项目或ERP级别的项目时,大多数情况下你需要使用union从具有多个表的数据库中获取数据。在下面的例子中,你可以看到如何在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);
v64noz0r

v64noz0r4#

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

相关问题