1

laravelのスコープを使用して、特定のcash_saleに属するすべてのcash_sales_itemsを合計しようとしています。問題は、これらのテーブルにいくつかの情報がある場合、コードは正常に機能しますが、テーブルが空の場合はエラーが発生することです

Object of class Illuminate\Database\Eloquent\Builder could not be converted to string  

以下はコードとテーブル構造です

accessories_cash_salesmysql> describe accessories_cash_sales;
+---------------+------------------+------+-----+---------+----------------+
| Field         | Type             | Null | Key | Default | Extra          |
+---------------+------------------+------+-----+---------+----------------+
| id            | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| client        | varchar(255)     | NO   |     |         |                |
| exchange_rate | int(11)          | NO   |     | 0       |                |
| employee_id   | int(10) unsigned | NO   | MUL | NULL    |                |
| status        | varchar(255)     | NO   |     |         |                |
| tax           | varchar(255)     | NO   |     |         |                |
| created_at    | timestamp        | YES  |     | NULL    |                |
| updated_at    | timestamp        | YES  |     | NULL    |                |
+---------------+------------------+------+-----+---------+----------------+

そしてもう一つは

mysql> describe accessories_cash_sales_items;
+--------------------------+------------------+------+-----+---------+----------------+
| Field                    | Type             | Null | Key | Default | Extra          |
+--------------------------+------------------+------+-----+---------+----------------+
| id                       | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| accessories_id           | int(10) unsigned | NO   | MUL | NULL    |                |
| quantity                 | int(11)          | NO   |     | 0       |                |
| amount                   | int(11)          | NO   |     | 0       |                |
| accessories_cash_sale_id | int(10) unsigned | NO   | MUL | NULL    |                |
| created_at               | timestamp        | YES  |     | NULL    |                |
| updated_at               | timestamp        | YES  |     | NULL    |                |
+--------------------------+------------------+------+-----+---------+----------------+

ブレードテンプレートでスコープメソッドを呼び出しています

\App\AccessoriesCashSale::paidOrCollected()

現金販売モデルの PayedOrCollected 関数は次のようになります

public function scopePaidOrCollected($query){
    $amount = 0;
    $items = $query->where('status', '=', 'paid')->orWhere('status', '=', 'Collected')->whereMonth('created_at','=', date('m'))->get();

    foreach($items as $item){
        $amount = $amount + $item->accessoriesCashSalesItems()->sum('amount');;
    }

    return $amount;
}
4

1 に答える 1