簡體   English   中英

Laravel Eloquent ORM混亂

[英]Laravel Eloquent ORM confusion

我試圖通過Eloquent實現以下目標:

我想查詢我的數據庫,計算status ='waiting'和'inprogress'的行數,但我遇到了以下問題。 如果我運行get()然后嘗試計數,我會被告知我不能在非對象上。 如果我嘗試運行get()之后,我會收到此錯誤: Undefined property: Laravel\\Database\\Query::$source

這是我的兩次嘗試:

//get() before
$devs = Dev::todo($user_id)->get(array('id', 'type', 'title', 'source', 'priority', 'status', 'for_user', 'priority', 'desc', 'created_at'));
$devs->num_waiting = $devs->where('status', '=', 'waiting')->count();
$devs->num_inprogress = $devs->where('status', '=', 'inprogress')->count();

//get() after
$devs = Dev::todo($user_id);
$devs->num_waiting = $devs->where('status', '=', 'waiting')->count();
$devs->num_inprogress = $devs->where('status', '=', 'inprogress')->count();
$devs->get(array('id', 'type', 'title', 'source', 'priority', 'status', 'for_user', 'priority', 'desc', 'created_at'));

我的待辦事項:

public static function todo($user_id) {

    $todo = Dev::where('for_user', '=', $user_id)
               ->where(function($query) {
                        $query->where('status', '=', 'active')
                              ->or_where('status', '=', 'inprogress')
                              ->or_where('status', '=', 'waiting');
                })
               ->order_by('priority', 'asc')
               ->order_by('created_at', 'desc');

    return $todo;
}

在計算我需要計算的數據之后如何運行get(),為什么會發生這種情況,還有更好的方法嗎?

在不查看Eloquent源代碼的情況下,我猜測count()基於SQL聚合函數COUNT()。 聚合函數返回聚合結果。 它們不返回構成聚合的行。

我希望這行(來自你的代碼)給你計數。

$devs->num_waiting = $devs->where('status', '=', 'waiting')->count();

如果我需要構成計數的行,我會根據應用程序執行其中一項操作。

  1. 避免使用count()方法,get()結果集,並計算集合中的項目。 在我的腦海中,我認為get()返回一個類型為“collection”的對象。 查找返回集合大小的方法。
  2. 使用相同的where()參數運行第二個查詢,並使用並發和競爭條件的后果。

這里的問題是get()返回一個不包含where()方法的Collection ,所以你需要在get()之前做where() get() 幸運的是,你的get()似乎取代了select()所以你應該使用它。

嘗試這個...

$devs = Dev::todo($user_id)->select(array('id', 'type', 'title', 'source', 'priority', 'status', 'for_user', 'priority', 'desc', 'created_at'));

現在,你應該能夠運行數過,但這樣做兩次行不通的,因為第二計時間將被計數waitinginprogress 我們可以創建另一個對象來查找其他計數,但它在性能上也不是很好,因為您運行的查詢基本相同3次。 兩個用於計數,一個用於返回實際的集合。 我要做的是獲取你的收藏,並在迭代它時使用php計算它。

$devs = Dev::todo($user_id)
    ->select(array('id', 'type', 'title', 'source', 'priority', 'status', 'for_user', 'priority', 'desc', 'created_at'))
    ->get();


$nWaiting = 0;
$nProgress = 0;
foreach($devs as $dev) {

    switch($dev->status) {
        case 'waiting':
            $nWaiting++;
            break;

        case 'inprogress':
            $nProgress++;
            break;

        default:
            break;
    }
}
    $devs->num_waiting = $nWaiting;
    $devs->num_inprogress = $nProgress;

此代碼未經測試,因為我不確定您使用todo()函數做了什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM