代码之家  ›  专栏  ›  技术社区  ›  Mike

使用多个表组合成一个表的laravel雄辩模型(没有单独的模型)

  •  0
  • Mike  · 技术社区  · 6 年前

    我正在开发一个rest api,它很苗条,很有说服力。 我以前用过Medoo DB。它工作得很好,但是我想删除静态模式并变得更加灵活。

    我有一个包含产品信息的数据库表。问题是我还有很多产品信息表。它们不是自己用的,只是与产品结合使用。

    因此,为每个子表创建雄辩的关系类和模型是没有意义的,因为它们永远不会在那里单独使用。它实际上是一个表扩展到多个表上。

    我知道最好的方法是改变数据库结构并创建一个大表,但我现在不能这样做。

    所以在medoo中,我定义了一个模式结构,其中包含所有可连接的表和一个选择一个产品的查询。就像我说的,我希望保持灵活性,不在代码中定义模式,但目前我只能从主表中选择数据。

    所以这里只有产品型号:

    <?php
    namespace Product\Models;
    
    use Interop\Container\ContainerInterface;
    #use Medoo\Medoo;
    use \Illuminate\Database\Query\Builder;
    use \Illuminate\Database\Eloquent\Model as Model;
    use \Illuminate\Database\Capsule\Manager;
    
    use \Psr\Http\Message\ServerRequestInterface as Request;
    use \Psr\Http\Message\ResponseInterface as Response;
    
    
    class Object extends Model
    {
        protected $database;
    
        public function __construct($database)
        {           
            $this->setTable('product_objects');
            $this->database = $database;
        }
    
        public function getObjectById($id) {
    
            /*       
            $data = $this->database
                ->table('product_objects')
                ->get($columns)
                ->first()
                ;
            */
    
            $data = $this->find($id); // this works (with one table)
    
    
            // Throw error if no result found.
            if (empty($data)) {
                throw new \Exception('No object found', 400);
            }        
    
            return $data;
        }
    }
    
    // this was just a test
    class Freetext extends Model
    {
        protected $database;
    
        public function __construct($database)
        {           
            $this->setTable('product_freetext');
            $this->database = $database;
        }
    }
    

    有没有可能做如下事情:

    $data = $this->find($id)->product_freetext->product_table3->product_table4 ...
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Mike    6 年前

    到目前为止,我通过插入连接其他表的scope方法解决了这个问题。 也许有人有更好的方法?

    public function scopeObjects($query) {
      return $query->join('product_freetext', 'product_freetext.oid', '=', 'product_objects.id');
    }
    

    然后

    $data = $this->objects()->find($id);