2017-02-28 152 views
0

DB::table('my_table')->get()返回Collection StdClass返回Laravel DB :: table('...') - > get()作爲Model的集合而不是StdClass

是否有可能返回MyTable而不是StdClass的集合?是否有這樣做的「laravel方式」?

要ilustrate我的問題,我有這個疑問在我的模型Item

 return DB::table('attribute_values') 
      ->join('items_categories', 'attribute_values.item_category_id', '=', 'items_categories.id') 
      ->where('items_categories.item_id', '=', $this->id) 
      ->select('attribute_values.*') 
      ->get(); 

,我需要模型AttributeValue的集合。目前我正在遍歷stdClass的集合並實例化AttributeValue。

+2

你可以使用'Eloquent'。 – PawelMysior

回答

2

您需要根據attrubute_values及其關係創建模式,例如

class ItemCatogory extends Illuminate\Database\Eloquent\Model { 
     protected $table = "item_categories"; 

     public attributeValues() { 
      return $this->hasMany(AttributeValue::class); 
     } 
} 

class AttributeValue extends Illuminate\Database\Eloquent\Model { 
    public itemCategories() { 
      return $this->belongsTo(ItemCategory::class); 
    } 
} 

然後你就可以查詢該型號:

return AttributeValues::with("itemCategories")->get(); //eager loading of relationship 

您還可以延遲加載的關係:

$attrValue = AttributeValues->first(); //Relationship not loaded 
$categories = $attrValue->itemCategories()->get(); 
+0

謝謝@apokryfos!我沒有提到,但是'ItemCatogory'是一個'Pivot'類。我知道在某些情況下,我可以像你一樣定義Eloquent關係,但在這種情況下,我需要執行一些查詢並將結果作爲模型對象而不是stdClass。 – Victor

+0

這應該仍然在這種情況下工作,但我不認爲你可以認爲'item_category'表是'item'和'category'之間的mn關係的數據透視表(我假設)它有關係時本身。你應該將itemcategory看作它自己的實體。 – apokryfos

+0

你完全正確。我的錯誤是使用'item_category'作爲Pivot而不是Model。非常感謝您打開我的想法。 – Victor

0

現在是那麼明顯,但如果它可以幫助別人,在這裏我是怎麼做的:

//it returns a Collection of StdClass 
return DB::table('attribute_values') 
    ->join('items_categories', 'attribute_values.item_category_id', '=', 'items_categories.id') 
    ->where('items_categories.item_id', '=', $this->id) 
    ->select('attribute_values.*') 
    ->get(); 

以及如何返回一個集合的雄辯模型:

//it returns a Collection of AttributeValue (my model class) 
return AttributeValue::join('items_categories', 'attribute_values.item_category_id', '=', 'items_categories.id') 
    ->where('items_categories.item_id', '=', $this->id) 
    ->get(); 
相關問題