php - 如何在 laravel eloquent 中使用子字符串?

标签 php sql laravel laravel-5

我有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/

相关文章:

php - 使用实例配置文件凭据签署 S3 上传策略

PHP Mysql单选按钮选择

c# - 如何在 asp.net 中显示 response.write

.net - 带有 MySQL 的 Asp.net Web 应用程序

javascript - 拉维尔 : Data-table search option not working using relationship table field

php - 通过 get 传输数据,url 中的 php 和安全性

php - 什么会导致 CI​​ 错误地返回空值?

php - 是否可以在 SQL 中使用 if 语句?

php - 分页符上的 dompdf 表格宽度问题

php - 调用未定义函数 mb_strimwidth