我有2个相关的表,问题是其中一个带来了每个用户的客户,但客户代码主要基于4位数字,问题是有很多用户拥有超过4位数字8或9这代表了你在公司的任务。但我只需要带上与表建立关系所需的前 4 个,并且只能带上公司名称
我正在像这样处理 sql 中的子字符串
$client = DB::connection('dpnmwin')->table('nmtrabajador')->select('SUBSTRING'('COD_UND', 1, 4))->where('CONDICION', '=', 'A')->get()
但这标志着我在同一个代码编辑器中犯了错误。
如何使用子字符串或其他方式做到这一点?
模范员工
class Employee extends Model
{
protected $connection = 'dpnmwin';
protected $table = 'nmtrabajador';
protected $primaryKey = 'CODIGO';
public function client(){
return $this->belongsTo('App\Client', 'COD_UND');
}
public function position(){
return $this->belongsTo('App\Position', 'COD_CARGO');
}
}
模型客户端
class Client extends Model
{
protected $connection = 'dpnmwin';
protected $table = 'nmundfunc';
protected $primaryKey = 'CEN_CODIGO';
public function employee(){
return $this->hasMany('App\Employee');
}
}
文件list.blade.php
@foreach ($users as $user)
<tr>
<td>{{$user->CEDULA}}</td>
<td>{{$user->NOMBRE}}</td>
<td>{{$user->APELLIDO}}</td>
<td>{{$user->EMAIL}}</td>
<td>{{$user->position->CAR_DESCRI}}</td>
<td>{{$user->client->CEN_DESCRI}}</td>
<td><a href="{{ route('detailUser', ['user_id' => $user->CODIGO]) }}"><i class="fas fa-user"></i></a></td>
</tr>
@endforeach
最佳答案
使用\DB::raw()
进行选择
:
$client = DB::connection('dpnmwin')->
table('nmtrabajador')->
select(\DB::raw('SUBSTRING(COD_UND, 1, 4) as COD_UND'))->
where('CONDICION', '=', 'A')->
get()
关于php - 如何在 laravel eloquent 中使用子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50573088/