【问题标题】:How to retrieve a column with another name in many-to-one Eloquent relationship如何在多对一 Eloquent 关系中检索具有另一个名称的列
【发布时间】:2019-09-12 23:50:01
【问题描述】:

我刚刚在 Laravel 开始了一个新项目。我希望它是多语言的,所以有些表对每种语言都有一个字段,例如:

Continent
 id
 en (for English)
 pt (for Portuguese)
 es (for Spanish)

这样:

1 'America', 'América', 'America'
2 'Africa', 'África', 'África'

同样,我有一个“区域”表。

我的大陆模型已经有:

public function regions() {
        return $this->hasMany(Region::class);
    }

我的目标是在运行时重命名列,这样我就可以使用“Continent->name”或“Region->name”,而不是“Continent->en”和“Region->en”。

到目前为止,我可以通过这种方式取得成果:

ContinentController@index

public function index() {
    $lang = 'en';

    $continents = DB::table('continents')->rightJoin('regions', 'continent_id', '=', 'continents.id')->select("continents.$lang AS continent_name", "regions.$lang AS region_name")->get();

    return view('geo.continents.index', compact('continents'));
}

不过,这给我带来了一张桌子:

@section('content')
    @foreach ($continents as $continent)
    {{ $continent->region_name }} {{ $continent->continent_name }} 
    @endforeach
@endsection

Central America (America)
Caribbean (America)
North America (America)
South America (America)

我想完成类似的结果,但使用 Eloquent 风格。像这样的:

$continents = Continent::select('continents.en AS name')->with('regions')->get();

到目前为止,我可以将大陆名称作为“名称”属性。如何将区域名称作为“名称”属性获取,例如:

$大陆->名称; $region->名称;

【问题讨论】:

  • 你不会只做$continent->{$lang}$region->{$lang} 吗?如果你已经有了,你不应该做一个复杂的SELECT AS/JOIN 等等。
  • @TimLewis:如果我是新的,那就这么简单......谢谢!那行得通!!!
  • 没问题!唯一需要注意的是,您需要将$lang$continent$region 一起传递给所有视图/函数,如果$whatever->{$lang}null 等则处理问题;但如果你牢记这一点,应该很简单。干杯!

标签: laravel eloquent


【解决方案1】:

您想查看scopes

// Continent.php

public function scopeRegion($query, $region)
{
        return $query->where('region', $region);
}

然后在你的控制器中,

Continent::region('en')->get();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-08
    • 2023-04-04
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 2014-02-03
    相关资源
    最近更新 更多