PHP OOP - 如果不呼叫另一個方法則傳回結果 $obj->get() 和 $obj->get()->count()
P粉742550377
P粉742550377 2024-04-01 12:28:10
0
1
413

很難準確地解釋我想要什麼,但我必須嘗試......

Laravel Eloquent 啟發我寫一個簡單的 php 類別來使用資料庫。

據我們所知,我們可以在 Laravel 中做到這一點:

$run = DB::table('users')->where('id', 3)->where('level', 2)->get();

我們也這樣做:

$run = DB::table('users')->where('id', 3)->where('level', 2)->get()->count();

我們也可以這樣做:

$run = DB::table('users')->where('id', 3)->where('level', 2)->get()->first();

我們也能做到:

$run = DB::table('users')->where('id', 3)->where('level', 2)->get()->pluck('id')->toArray();

我從未嘗試過,但我相信它也有效:

$run = DB::table('users')->where('id', 3)->where('level', 2)->get()->pluck('id')->toArray()->first();

問題是「它是如何運作的?」

#我應該如何編寫才能以任何方式返回合適的結果?

// It was easy to write my code to return total results if I write like that
$run = DB::from('users')->where('id', 3)->where('level', 2)->get()->count();

// Or to return first result if I write like that
$run = DB::from('users')->where('id', 3)->where('level', 2)->get()->first();

// But what sould I do to return all the results if write like that (As eloquent works).
$run = DB::from('users')->where('id', 3)->where('level', 2)->get();

我需要類似「if - else case for method」的東西,例如:

function __construct() {
   if(if aint`t no calling any methods except **get()** ){
      // Lets return default method
      return $this->results();
   }
   else{
      // Do whatever...
   }
}

這是我的完整程式碼:

https://github.com/amirandev/PHP-OOP-DB-CLASS/blob/main/db.php

P粉742550377
P粉742550377

全部回覆(1)
P粉536532781

據我所知,當你嘗試類似的事情時

$run = DB::from('users')->get()->count();

您獲得所有用戶和 php/laravel 計數用戶,這意味著

$users = DB::from('users')->get(); // get all users
$usersConut = $users->count();  //count them away of database/mysql

first() 相同

當您使用此程式碼DB::from('users')->count(); 時,您實際上是在向MySql 詢問計數,而不是在後端對它們進行計數。

我強烈建議使用這個套件barryvdh/laravel-debugbar來幫助您查看資料庫奎里斯。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!