5
votes

I noticed that I write the database table names quite a lot, and in different files, when I use the Query Builder. If I were to change the database table names, I would have to search and change quite many rows in my project. Is this an issue your Laravel guys noticed and come up with an solution to?

I like the Eloquent approach which uses class models, instead of database names; but for some queries I think the Query Builder is a better solution (though I am no expert in this matter).

4

4 Answers

8
votes

Use this in your query :

(new YourModel())->getTable()

Example :

DB:raw('SELECT * FROM '.(new User())->getTable().' WHERE id=3');
6
votes

If you already have a queryBuilder object you can obtain the table name like

$tableName = $query->getModel()->getTable();

0
votes

How about using OOP concept. Laravel is a framework, so no one stops you from using basic PHP OOP concept. This is what I do:

Consider my query is like :

$result=DB::table('myTable')->select()->get();

What I do is make a class that holds all the tablenames :

class TableName
{
    private $tableName= "myTable";
    public function getTableName()
    {
        return $this->tableName;
    }

    public function setTableName($table_name)
    {
        $this->tableName = $table_name;
    }
}

Now all i have to do is call a method using an object in the file I want to use the table like :

$name = new TableName() ;
$result=DB::table($name->getTableName())->select()->get();

Use wherever you want. I don't think its the best solution however it works for me. Hope it helps

0
votes

Maybe you can extend the model class.

CModel extend Model {

   protected static $tableName;

   public static getTableName(){
       if(static::$tableName)
          return static::$tableName;

       /* if you create a "reference break" you don't have to *
       /* create "protected static $tableName" row in your all model */

       $table = (new static())->getTable();
       return static::$tableName = &$table;
   }
}

YourModel extends CModel {...}

than you can use

YourModel::getTableName()

I'm not have better idea.