简体   繁体   中英

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.

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,

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

union all then laravel query builder provide unionAll method for mysql union. 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. In Following example you can see how to use union all in Laravel 5.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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