首頁  >  問答  >  主體

PHP OOP - 如果不呼叫另一個方法則傳回結果 $obj->get() 和 $obj->get()->count()

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

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粉742550377P粉742550377182 天前414

全部回覆(1)我來回復

  • P粉536532781

    P粉5365327812024-04-02 09:51:57

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

    $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來幫助您查看資料庫奎里斯。

    回覆
    0
  • 取消回覆