2013-12-17 75 views
2

我在玩Laravel模型,我需要返回一個不在數據庫表中的值,但它是通過運行模型方法來實現的。此方法運行一個查詢,該查詢對分組結果進行分組和計數。無法在模型構造函數中分配變量值

模型方法工作得很好,但我似乎並沒有能夠在構造函數中比0

不同的東西預先填寫$量可變因此,這是該模型的摘錄:

public $quantity; 

function __construct($attributes = array(), $exists = false) { 
    parent::__construct($attributes, $exists); 
    $this->quantity = $this->quantity(); 
} 

public function quantity() 
{ 
    $query = DB::table('carts_shopping') 
      ->select('cart_id', DB::raw('COUNT(*) AS quantity')) 
      ->where('cart_id',$this->cart_id) 
      ->groupBy('cart_id') 
      ->first(); 
    return ($query) ? $query->quantity : 0; 
} 

雖然這是怎麼了正在嘗試從控制器的結果:

$cartitems = Auth::user()->cartshopping; 

foreach ($cartitems as $cartitem) 
{ 
    echo $cartitem->name; 
    echo $cartitem->quantity; 
} 

正如你可能猜到「cartshopping」來自用戶模型存在關聯d與我粘貼的模型片段。

我還注意到quantity()方法被調用,並且它始終返回0,就像$ this-> cart_id是空的一樣,並且用實際值更改$ this-cart_id,查詢本身甚至不會執行。

非常感謝你們分享的任何建議。

+0

你試過var_dump($ query);在返回之前?它可能不包含你的想法,或者它可能實際上是0. – vascowhite

+0

剛剛嘗試過:不幸的是,dd($ query);返回NULL。 相同的結果設置 - >其中('cart_id',23)'23'是已知值。 –

+0

然後您的查詢沒有返回任何結果。 – vascowhite

回答

1

您是否嘗試過使用$ this-> attributes訪問屬性?

public $quantity; 

function __construct($attributes = array(), $exists = false) { 
    parent::__construct($attributes, $exists); 
    $this->quantity = $this->quantity(); 
} 

public function quantity() { 
    $query = DB::table('carts_shopping') 
      ->select('cart_id', DB::raw('COUNT(*) AS quantity')) 
      ->where('cart_id', $this->attributes['cart_id']) 
      ->groupBy('cart_id') 
      ->first(); 
    return ($query) ? $query->quantity : 0; 
} 

如果失敗了,你可以嘗試使用Eloquent訪問器,這將是最好的方法。這也會使其變得動態,這可能是有用的。

class YourModel { 

    // Normal model data here 

    public function getQuantityAttribute() { 
     $query = DB::table('carts_shopping') 
      ->select('cart_id', DB::raw('COUNT(*) AS quantity')) 
      ->where('cart_id', $this->attributes['cart_id']) 
      ->groupBy('cart_id') 
      ->first(); 
     return ($query) ? $query->quantity : 0; 
    } 

} 
+0

感謝您的努力Ollieread,剛剛嘗試過,結果引發異常:未定義索引:cart_id。我想知道問題是否以Laravel構建模型和構造函數的方式駐留在其他位置。 關於雄辯的訪問者,這是我的第一個想法,但我後來從Laravel文檔中理解,他們習慣於「在獲取或設置它們時變換模型屬性」。而我的$數量屬性模型本身不存在...我只是自己計算它的方法。我誤解了訪問者章節嗎? –

+1

訪問器可以以這種方式使用,但它們也可以用來添加不存在的屬性。我給出的上述代碼可以打包以確保$ this-> attributes ['cart_id']存在,但它應該可以工作。舉個例子,我的表中有'active' int(1),但是我有getIsActiveAttribute()訪問器,它將爲$ model-> is_active返回布爾值。嘗試刪除您的自定義構造函數,並確保該對象存在之前。 – ollieread

+0

好吧......切換到「訪問器」技術就像一個魅力。現在我有我的 - >數量返回正確的結果,但我沒有使用$ this->屬性['cart_id']技巧,$ this-> cart_id工作得很好。 –

相關問題