【问题标题】:Laravel equivalent if statementLaravel 等效的 if 语句
【发布时间】:2020-10-13 15:51:39
【问题描述】:

我是初学者 php 开发人员。 我在 Laravel 8 中制作我的项目。

我有这个迁移:

Schema::create('clients', function (Blueprint $table) {
    $table->id();
    $table->string('email');
    $table->integer('type')->comment('1 - Client individual , 2 - Client Company');
    $table->string('crm_number')->unique();
    $table->string('password');
    $table->string('verify_token');
    $table->rememberToken();
    $table->timestamp('password_assigned_at')->nullable();
    $table->timestamp('email_verified_at')->nullable();
    $table->timestamps();
    $table->deactivation();
    $table->softDeletes();

    $table->unique(['email', 'deleted_at']);
});

Schema::create('client_infos', function (Blueprint $table) {
    $table->id();
    $table->foreignId('client_id')->constrained('clients')->onDelete('cascade');
    $table->string('first_name');
    $table->string('last_name');
    $table->string('phone_nr')->nullable();
    $table->timestamps();
});

Schema::create('client_company_infos', function (Blueprint $table) {
    $table->id();
    $table->foreignId('client_id')->constrained('clients')->onDelete('cascade');
    $table->string('name');
    $table->string('nip')->nullable();
    $table->string('phone_nr')->nullable();
    $table->string('contact_email')->nullable();
    $table->string('invoice_email')->nullable();
    $table->timestamps();
});

如果 client.type = 1 - 客户个人,2 - 客户公司

我有这个代码:

Client::leftJoin('client_company_infos', 'client_company_infos.client_id', '=', 'clients.id')
    ->leftJoin('client_infos', 'client_infos.client_id', '=', 'clients.id')
    ->select('clients.*',
        'client_company_infos.name as name',
        'client_infos.first_name as first_name',
        'client_infos.last_name as last_name',
    );

在我的情况下,我有 name - 公司名称,first_name 为名字,last_name 为 last_name。

我总是需要一个值“名称”:

  1. 公司 = 名称
  2. 个人用户 = 名称为“名字 + 姓氏”

我该怎么做?

请帮帮我

【问题讨论】:

  • 你可以使用访问器和修改器

标签: php laravel


【解决方案1】:

您可以为此使用访问器,例如


class YourModel extend Model
{
   //foo bla bla

  public function getFullNameAttribute()
  {
     return sprintf('%s %s',$this->name,$this->lastname;
  }
}

使用


User::find(63);

echo $user->full_name;

relevent document

【讨论】:

  • 谢谢,我知道这个解决方案。但是,我需要在 joiny 或 selectRaw 中进行
  • 对于加入你可以用 map 或 walk 方法进行集合覆盖,laravel 每次都从 db 返回集合......或者你可以 concat 是 sql raw
  • DB::raw('CONCAT(lname ", ", lastanme) AS full_name
  • 这并不完全是一个解决方案。我需要根据用户是否是公司来编写“名称”:client_company_infos.name oub 如果是个人:name = client_infos.last_name + last_name
  • 那你不在查询中使用if语句?
猜你喜欢
  • 2021-06-04
  • 2011-01-27
  • 1970-01-01
  • 2018-03-25
  • 1970-01-01
  • 1970-01-01
  • 2016-02-02
  • 1970-01-01
  • 2018-08-06
相关资源
最近更新 更多