2017-12-27 33 views
0

Laravelを初めて使用しています。 Eloquent Modelを使用してDBのデータにアクセスしようとしています。Eloquentモデルでテーブル名を動的に設定する方法

テーブル名などの類似点を共有するテーブルがあります。

私は、以下のようなDBの複数のテーブルにアクセスするために1つのモデルを使用したいと思いますが、運がありません。

テーブル名を動的に設定する方法はありますか?

何か提案やアドバイスをいただければ幸いです。前もって感謝します。

モデル:

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が提案しました。

そして私は

$productLog = new ProductLog; 
$productLog->setTable('LogEmail'); 

$logInstance = $productLog->where('origin_id', $carrier_id) 
          ->where('origin_type', 2); 
+0

、あなたは別のテーブル名を毎回渡したいですか? –

+0

はい。特定のテーブルのみ。類似の属性を持つ表 – smchae

+0

私はあなたがすべてのテーブルのモデルを作ることを提案できますが、モデル名をその関数に渡すことでモデルのオブジェクトを作る共通の関数を教えて、モデルオブジェクトを動的に得ることができます。 –

答えて

2

の下に、以下の形質は水和中に、テーブル名を渡すことが可能になりますようにすることによってどこ条件を追加することができました。ここで

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 Product extends Model 
{ 
    use BindsDynamically; 
} 

は次のようにインスタンスのメソッドを呼び出しますので

public function index() { 

    $productLog = new ProductLog; 

    $productLog->setTable('anotherTableName'); 

    $productLog->get(); // select * from anotherTableName 

    etc... 

    $productLog->myTestProp = 'test; 
    $productLog->save(); // now saves into oooops 
} 
+0

テーブル名は変更されますが、 '$ productLog-> setTable(anotherTableName ');'を使用した後、 '$ productLog-> where(' some query ')'を使用すると動作しません。 – smchae

関連する問題