php - 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 ...
解决方案
到目前为止,我通过插入一个连接其他表的范围方法来解决它。也许有人有更好的方法?
public function scopeObjects($query) {
return $query->join('product_freetext', 'product_freetext.oid', '=', 'product_objects.id');
}
接着
$data = $this->objects()->find($id);
推荐阅读
- css - 需要将 div 内的元素对齐到同一行
- javascript - 显示/隐藏具有多种可能性的列表元素
- visual-studio-code - 在 VSCode 中,如何选择带有 - 的整个单词?
- python - 使用 sqlite3 在 Python 中创建数据库
- django - Django 模板:在不同列表上组合 2 个循环
- opengl - 访问原语 id/index 顶点属于 glsl:vertex-shader
- hadoop - 如何使用 Java 将 zip 文件直接从 URL 传输到 HDFS?
- azure - 使用 azure 应用服务部署槽运行不同的应用?
- winapi - Windows上的隐式进程间共享内存?
- ios - 使用 Airplay 时如何为 tvOS 信息面板填充元数据信息?