由于 laravel 中的内部联接,object 的 属性 名称不明确

ambiguous in property names of object due to inner join in laravel

我使用以下代码在我的控制器中加入两个 tables

$clientdata = DB::table('clients')
 ->join('users', 'clients.id', '=', 'users.id')->get();

在blade中:

@foreach($clientdata as $clientdata)
<td>{{$clientdata->first_name(client)}}</td>
<td>{{$clientdata->last_name(client)}}</td>
<td>{{$clientdata->first_name(users)}}</td>
<td>{{$clientdata->last_name(users)}}</td>
@endforeach

但是我的 table 客户和用户都包含与 first_namelast_name 同名的列,我想访问 first_namelast_name 客户 table 和用户 table,那么我该怎么做

你可以做到

$clientdata = DB::table('clients')
   ->join('users', 'clients.id', '=', 'users.id')
   ->select(
       'users.first_name as users_first_name',
       'users.last_name as users_last_name',
       'clients.first_name as clients_first_name',
       'clients.last_name as clients_last_name',
   )
   ->get();

在您的 blade 文件中:

@foreach($clientdata as $data)
<td>{{$data->users_first_name}}</td>
<td>{{$data->users_last_name}}</td>
<td>{{$data->clients_first_name}}</td>
<td>{{$data->clients_last_name}}</td>
@endforeach

试试这个代码

     DB::table('clients') ->join('users', 'clients.id', '=', 'users.id')->select('clients*', DB::raw('clients as client_name'))->get();

我一直使用这个解决方案

懒惰的一个:)(在列数较多的情况下)

我 select 两个 table 中的所有列 (table.*),并且我添加了带有别名的模糊列 (table.ambiguous_1 作为别名)

例子

$clientdata = DB::table('clients')
->join('users', 'clients.id', '=', 'users.id')
->select(
   'users.*',
   'clients.*',
   'users.first_name AS users_first_name',
   'users.last_name AS users_last_name',
   'clients.first_name AS clients_first_name',
   'clients.last_name AS clients_last_name',
)
->get();

在 blade 中,我对不明确的列使用别名,而在其他列中使用原始列名。