如何在 Laravel 中动态 select 需要的列
How to dynamicly select needed columns in Laravel
大家好,我有一个 table,其中包含不同语言的内容。像这样:
id, name_en, name_de
现在,当我使用 Eloquent 请求数据时,我总是这样做:
Product::with(['offers', 'category'])->select(['id', getLocalValue('name'))->find($id);
函数 getLocalValue 正在获取浏览器语言,selects 当前列并将其返回为 "name"。所以当浏览器语言是英语时,我得到的数据如
{"id" => 1,
"name" => "Englisch name"
}
我的问题:我在很多 table 关系中有很多多语言内容。当使用 ->select() 函数时,我必须将我想要请求的所有列放在这里。其实我想做的就是得到一切。但是对于由于多语言而在不同列中的数据,它应该取所需的列(如 name_en)并在没有 _en(名称)的情况下返回。
我希望你明白我的意思,并能在这里帮助我 :( 谢谢你的时间!!!gerti
正如我在上面评论的那样,我将更改数据结构,使语言名称按名称单独 table。然后,如果要使用浏览器语言进行检测,可以使用这个直接根据语言设置table。
将此添加到您的 productName
型号:
protected static $_table;
public function setTable($prefix)
{
static::$_table = $prefix.'_productNames';
return $this;
}
public function getTable()
{
return static::$_table;
}
public function Product () {
return $this->belongsTo('Product');
}
并将此添加到您的 Product
模型中:
public function productName () {
return $this->hasOne('productName');
}
现在您可以通过以下方式设置您打算使用的table:
$productName = new productName;
$productName->setTable(strtolower(getLocalValue('name')));
据此,您的 table 必须命名为
de_productNames
举个例子。
现在您可以像这样使用您的查询:
$productName = new productName;
$productName->setTable(strtolower(getLocalValue('name')));
Product::with(['offers', 'category','productName'])->find($id);
我不确定你的 getLocalValue()
是做什么的,strtolower 只是为了适应 table 名称,如果 getLocalValue() 已经为你做了这个,就把它去掉。
大家好,我有一个 table,其中包含不同语言的内容。像这样:
id, name_en, name_de
现在,当我使用 Eloquent 请求数据时,我总是这样做:
Product::with(['offers', 'category'])->select(['id', getLocalValue('name'))->find($id);
函数 getLocalValue 正在获取浏览器语言,selects 当前列并将其返回为 "name"。所以当浏览器语言是英语时,我得到的数据如
{"id" => 1,
"name" => "Englisch name"
}
我的问题:我在很多 table 关系中有很多多语言内容。当使用 ->select() 函数时,我必须将我想要请求的所有列放在这里。其实我想做的就是得到一切。但是对于由于多语言而在不同列中的数据,它应该取所需的列(如 name_en)并在没有 _en(名称)的情况下返回。
我希望你明白我的意思,并能在这里帮助我 :( 谢谢你的时间!!!gerti
正如我在上面评论的那样,我将更改数据结构,使语言名称按名称单独 table。然后,如果要使用浏览器语言进行检测,可以使用这个直接根据语言设置table。
将此添加到您的 productName
型号:
protected static $_table;
public function setTable($prefix)
{
static::$_table = $prefix.'_productNames';
return $this;
}
public function getTable()
{
return static::$_table;
}
public function Product () {
return $this->belongsTo('Product');
}
并将此添加到您的 Product
模型中:
public function productName () {
return $this->hasOne('productName');
}
现在您可以通过以下方式设置您打算使用的table:
$productName = new productName;
$productName->setTable(strtolower(getLocalValue('name')));
据此,您的 table 必须命名为
de_productNames
举个例子。
现在您可以像这样使用您的查询:
$productName = new productName;
$productName->setTable(strtolower(getLocalValue('name')));
Product::with(['offers', 'category','productName'])->find($id);
我不确定你的 getLocalValue()
是做什么的,strtolower 只是为了适应 table 名称,如果 getLocalValue() 已经为你做了这个,就把它去掉。