首页 > 解决方案 > Laravel Eloquent 模型使用多个表合并为一个(没有单独的模型)

问题描述

我正在使用 Slim 和 Eloquent 开发 REST API。我以前用过 Medoo DB。它运行良好,但我想删除静态模式并变得更加灵活。

我有一个包含产品信息的数据库表。问题是我有更多包含产品信息的表格。这些不是为自己使用,而是仅与产品结合使用。

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

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

所以在 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 ...

标签: phplaravelormeloquentslim

解决方案


到目前为止,我通过插入一个连接其他表的范围方法来解决它。也许有人有更好的方法?

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

接着

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

推荐阅读