Laravel 查询构建器和表名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39036338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Query builder and table names
提问by Olof84
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?
我注意到当我使用查询生成器时,我在不同的文件中写了很多数据库表名。如果我要更改数据库表名,我将不得不在我的项目中搜索和更改相当多的行。这是您的 Laravel 人员注意到并提出解决方案的问题吗?
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).
我喜欢 Eloquent 方法,它使用类模型而不是数据库名称;但是对于某些查询,我认为 Query Builder 是一个更好的解决方案(尽管我不是这方面的专家)。
采纳答案by Aditya Singh
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:
如何使用 OOP 概念。Laravel 是一个框架,所以没有人阻止您使用基本的 PHP OOP 概念。这就是我所做的:
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
随时随地使用。我不认为它是最好的解决方案,但它对我有用。希望能帮助到你
回答by neoteknic
Use this in your query :
在您的查询中使用它:
(new YourModel())->getTable()
Example :
例子 :
DB:raw('SELECT * FROM '.(new User())->getTable().' WHERE id=3');
回答by hovszabolcs
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.
我没有更好的主意。