在 Laravel 中通过 DB Builder 获取的视图中显示不明确的名称

Show ambiguous name in view fetched through DB Builder in Laravel

我正在从三个表中获取数据,其中两个表(departmentdata 和 cities)具有相同的字段 name。因此,当我在我的视图中显示名称字段时,它会显示结果集最后一次出现时名称字段的值。

//Controller source code
$leads = DB::table('leaddata')
->join('departmentdata', 'departmentdata.id', '=', 'leaddata.department')
->join('cities', 'cities.id', '=', 'leaddata.citydata')
->get();

// View source code
<?php foreach ($leads as $lead) {
?>
<span style="white-space: nowrap;">
    {{ $lead->name }}
<span>
<?php } ?>

如何分别选择部门名称和城市名称显示在视图中?

使用别名:

$leads = DB::table('leaddata')
->select('departmentdata.name AS department', 'cities.name AS city')
->join('departmentdata', 'departmentdata.id', '=', 'leaddata.department')
->join('cities', 'cities.id', '=', 'leaddata.citydata')
->get();

所以你可以:

<span style="white-space: nowrap;">
    {{$lead->department}} {{ $lead->city}} 
<span>