問題描述
我是 Laravel 的新手.我正在嘗試使用 Eloquent 模型訪問數據庫中的數據.
I am new to Laravel. I am trying to use Eloquent Model to access data in DB.
我有一些表具有相似性,例如表名.
I have tables that shares similarities such as table name.
所以我想使用一個模型來訪問數據庫中的多個表,如下所示,但沒有運氣.
So I want to use one Model to access several tables in DB like below but without luck.
有沒有辦法動態設置表名?
Is there any way to set table name dynamically?
任何建議或建議將不勝感激.提前致謝.
Any suggestion or advice would be appreciated. Thank you in advance.
型號:
class ProductLog extends Model
{
public $timestamps = false;
public function __construct($type = null) {
parent::__construct();
$this->setTable($type);
}
}
控制器:
public function index($type, $id) {
$productLog = new ProductLog($type);
$contents = $productLog::all();
return response($contents, 200);
}
解決方案對于那些遇到同樣問題的人:
我能夠按照@Mahdi Younesi 建議的方式更改表名.
I was able to change table name by the way @Mahdi Younesi suggested.
我可以通過如下方式添加 where 條件
And I was able to add where conditions by like below
$productLog = new ProductLog;
$productLog->setTable('LogEmail');
$logInstance = $productLog->where('origin_id', $carrier_id)
->where('origin_type', 2);
推薦答案
以下 trait 允許在 hydration 期間傳遞表名.
The following trait allows for passing on the table name during hydration.
trait BindsDynamically
{
protected $connection = null;
protected $table = null;
public function bind(string $connection, string $table)
{
$this->setConnection($connection);
$this->setTable($table);
}
public function newInstance($attributes = [], $exists = false)
{
// Overridden in order to allow for late table binding.
$model = parent::newInstance($attributes, $exists);
$model->setTable($this->table);
return $model;
}
}
使用方法如下:
class ProductLog extends Model
{
use BindsDynamically;
}
像這樣在實例上調用方法:
Call the method on instance like this:
public function index()
{
$productLog = new ProductLog;
$productLog->setTable('anotherTableName');
$productLog->get(); // select * from anotherTableName
$productLog->myTestProp = 'test';
$productLog->save(); // now saves into anotherTableName
}
這篇關于如何在 Eloquent 模型中動態設置表名的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!