Cast Laravel query results to class

前端 未结 6 1385
清酒与你
清酒与你 2021-02-02 12:04

When creating a query using the syntax DB::table(\'foo\'), it creates a generic class (stdClass). Is there any way to cast the resulting rows to a specific class?

6条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-02 12:42

    You cannot type cast it this way.
    You can build change Your Foo class to get handle of object and work with it.

    class Foo {
      private $object = null;
      public function __construct(stdClass $object) {
        $this->object = $object;
      }
    
      public function __get($property) {
        if (property_exists($this->object, $property)) {
          return $this->object->$property;
        }
      }
    
      public function __set($property, $value) {
        if (property_exists($this->object, $property)) {
          $this->object->$property = $value;
        }
        return $this;
      }
    
      public static function make(stdClass $object) {
        return new self($object);
      }
    
      public static function makeCollection(array $collection) {
        foreach($collection AS $key => $Item) {
          $collection[$key] = self::make($Item);
        }
        return $collection;
      }
    }
    
    $result = DB::table('foo')->get();
    $converted = Foo::makeCollection($result);
    

提交回复
热议问题