我正在使用Slim和Eloquent开发REST API。 之前我使用过Medoo DB。它工作得很好,但我想删除静态架构并获得更灵活。
我有一个包含产品信息的数据库表。问题是我有更多的产品信息表。这些不是用于自己,而是仅与产品结合使用。
因此,为每个子表创建Eloquent Relationship Classes和Model是没有意义的,因为它们永远不会在那里使用。事实上,它是一个扩展到多个表的表。
我知道最好的方法是更改数据库结构并创建一个大表,但我现在不能这样做。
因此,在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 ...
答案 0 :(得分:0)
到目前为止,我通过插入连接其他表的范围方法解决了这个问题。 也许有人有更好的方法?
public function scopeObjects($query) {
return $query->join('product_freetext', 'product_freetext.oid', '=', 'product_objects.id');
}
然后
$data = $this->objects()->find($id);