[英]Laravel fetch data from two tables without join with pagination
我想从两个表properties和properties_x中获取结果,其中properties.address
或properties_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
使用union all
来联合两个表的数据,
并从数据库中的这些数据中获取列,以便您可以使用分页。
像这样尝试:
$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 将两个数据表放在一起
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);
$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.