返回 Laravel DB::table('...')->get() 作为模型集合而不是 StdClass

Returning Laravel DB::table('...')->get() as a Collection of Model instead of StdClass

DB::table('my_table')->get() return 是 StdClass 的集合。

是否可以 return MyTable 的集合,而不是 StdClass?有没有"laravel way"这样做的?

为了说明我的问题,我在我的模型上有这个查询 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 的。

您需要根据 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(); 

现在很明显了,但如果对某人有帮助,我就是这样做的:

//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();

以及如何必须 return Eloquent 模型的集合:

//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();