重构查询构建器Laravel

发布于 2025-01-25 05:02:15 字数 322 浏览 2 评论 0原文

我想在几个表上进行重复获取数据并访问(请参见下面的示例)。有没有办法以清洁的方式编写代码,而不是为所有表重复相同的代码?

$xs = DB::table('table1')->where('text', 'like', '%string')->get();

foreach ($xs as $x) {
           ..
}

$ys = DB::table('table2')->where('text', 'like', '%string')->get();

foreach ($ys as $y) {
           ..
}```

I want to do repetitive get data and foreach on several tables (see example below). Is there a way to write the code in a cleaner way instead of repeating the same code for all the tables?

$xs = DB::table('table1')->where('text', 'like', '%string')->get();

foreach ($xs as $x) {
           ..
}

$ys = DB::table('table2')->where('text', 'like', '%string')->get();

foreach ($ys as $y) {
           ..
}```

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

深海夜未眠 2025-02-01 05:02:15

我的方法是使用数组和foreach

$tables = ['table1', 'table2'];
results = [];

foreach($tables as $table) {
  $data = DB::table($table)->where('text', 'like', '%string')->get();
  foreach($data as $d) {
    // your logic here
  }
  $results[] = ; // return a value from each query to array
}

My approach is using array and foreach

$tables = ['table1', 'table2'];
results = [];

foreach($tables as $table) {
  $data = DB::table($table)->where('text', 'like', '%string')->get();
  foreach($data as $d) {
    // your logic here
  }
  $results[] = ; // return a value from each query to array
}
定格我的天空 2025-02-01 05:02:15

您可以编写基本功能并将tableName传递给它并执行某些操作

public function getData($tableName) {
  $query = DB::table($tableName)->where('text', 'like', '%string')->get();
  foreach ($query as $row) {
          ...
   }

  // return result;
}

$tables = ['table1', 'table2', 'table3'];
$queryResponse = [];

foreach($tables as $tableName) {
    $queryResponse[$tableName] =  $this->getData($tableName);
}

You can write a base function and pass tableName to it and execute certain action

public function getData($tableName) {
  $query = DB::table($tableName)->where('text', 'like', '%string')->get();
  foreach ($query as $row) {
          ...
   }

  // return result;
}

$tables = ['table1', 'table2', 'table3'];
$queryResponse = [];

foreach($tables as $tableName) {
    $queryResponse[$tableName] =  $this->getData($tableName);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文